如何根据数组长度向值为 0 或 1 的嵌套数组添加索引 [英] How to add index to nested array with value 0 or 1 depending on array length

查看:22
本文介绍了如何根据数组长度向值为 0 或 1 的嵌套数组添加索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何完成这样的任务:我有一些数组:

I'm wondering, how to do task like this: I have some array:

var x = [
            {
                "place": 1,
                "name": 'Steve',
            },
            {
                "place": 4,
                "name": 'Ann',
            },
            {
                "place": 9,
                "name": 'John',
            },
        ];

现在我想添加新值,这将保留索引号,结果为:

Now i would like to add new value, that will keep index number, to have the result as:

var x = [
            {
                'index':0,
                "place": 1,
                "name": 'Steve',
            },
            {
                'index':1,
                "place": 4,
                "name": 'Ann',
            },
            {
                'index':2,
                "place": 9,
                "name": 'John',
            },
        ];

我已经尝试过这个,但似乎这是一个糟糕的解决方案并且不起作用:

I've tried this, but seems it's bad solution and not working:

for (var i = 0; i < x.length; i++) {
            arr.push(x['index'],i);
        }

感谢您的帮助,我不想变得贪婪,但如果也可以帮助解决以下问题,那将是额外的:是否可以将索引"值设置为 0 或 1,例如,如果我在数组中有 5 个项目,是否有任何方法可以使用模运算符检查循环并将索引值指定为 0,1,0,1,0?最好的问候.

Thanks for help with this, and i don't want to be greddy, but if would be also possible to help with the following it would be extra: Is it possible to have "index" values as 0 or 1, so if for example i have 5 items in array, is there any way to do check in the loop using modulo operaror and assign index value as 0,1,0,1,0? Best regards.

var x = [
            {
                'index':0,
                "place": 1,
                "name": 'Steve',
            },
            {
                'index':1,
                "place": 4,
                "name": 'Ann',
            },
            {
                'index':0,
                "place": 9,
                "name": 'John',
            },
            {
                'index':1,
                "place": 9,
                "name": 'John',
            },
            {
                'index':0,
                "place": 9,
                "name": 'John',
            },
        ];

推荐答案

你可以像这样使用 .forEach() 和模运算符:

You can use .forEach() and modulus operator like this:

var x = [
  {"place": 1, "name": 'Steve'},
  {"place": 4, "name": 'Ann'},
  {"place": 9, "name": 'John'}
];

x.forEach((o, i) => (o.index = i % 2));

console.log(x);

这篇关于如何根据数组长度向值为 0 或 1 的嵌套数组添加索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆