calculate and insert columns into array javascript

时间:2015-12-08 19:28:32

标签: javascript

I just know a little bit of javascript and appreciate if anyone can help for my question. I have an array like this:

foreach

I want to intert a column a1(a1=a-b) in the array.And intert name in only the first two rows of array. Eventually, I want to get the result like this:

var data = [
            {a:44,b:2},
            {a:50,b:5},
            {a:49,b:7},
            {a:41,b:6},
            {a:59,b:9},
            ]

Since I have thousands of rows, it's impossible to do it manually. Can anyone help to write down the code of this transition? Many thanks!

3 个答案:

答案 0 :(得分:1)

这假设ab是静态对象键!请注意,对象不会保留顺序。

data.forEach(obj => obj["a1"] = obj.a - obj.b);

这一个衬垫设置当前对象的a1等于a-b(+值转换为数字之前的+,以防字符串进入那里(有点多余)。添加名称,只需在箭头功能中添加括号(需要第二行,因此可读性),只需添加obj["name"] = "whatever";

答案 1 :(得分:1)

只需一行代码,即可:

var data = [
        { a: 44, b: 2 },
        { a: 50, b: 5 },
        { a: 49, b: 7 },
        { a: 41, b: 6 },
        { a: 59, b: 9 },
    ],
    insert = ['monkey', 'dog'];

data.forEach(function (a, i) {
    a.c = a.a - a.b;
    if (i in insert) {
        a.name = insert[i];
    }
});
document.body.innerHTML = '<pre>' + JSON.stringify(data, 0, 4) + '</pre>';

答案 2 :(得分:-1)

遍历前两个对象并添加首选属性

var data = [
    {a:44,b:2},
    {a:50,b:5},
    {a:49,b:7},
    {a:41,b:6},
    {a:59,b:9},
];

for (var i = 0; i < data.length; i++) {
    data[i].a1 = data[i].a - data[i].b;
    if (i == 0) { data[i].name = "monkey"; }
    if (i == 1) { data[i].name = "dog"; }
}