在javascript中修改数组结构

时间:2017-11-06 16:50:07

标签: javascript arrays

稍微更新(仅用于澄清"重复的问题标记")

这个问题与this one略有不同,因为在那里我们讨论了使用javascript循环数组的一些方法。就我而言,我们正在讨论如何修改'使用javascript的现有关联数组数组。这不是完全相同的概念,因为我的具体情况可以尝试应用与循环不同的东西。

我在Chrome浏览器中使用obj复制了此数据结构console.log

var obj = {
    key_1: [{
        prop_1: "some_value",
        prop_2: "some_value_2",
        prop_3: "some_value_3",
        prop_4: "some_value",
        prop_5: "some_value"
    }, {
        prop_1: "some_value",
        prop_2: "some_value_2",
        prop_3: "some_value_3",
        prop_4: "some_value",
        prop_5: "some_value"
    }],
    key_2: [{
        prop_1: "some_value",
        prop_2: "some_value_2",
        prop_3: "some_value_3",
        prop_4: "some_value",
        prop_5: "some_value"
    }, {
        prop_1: "some_value",
        prop_2: "some_value_2",
        prop_3: "some_value_3",
        prop_4: "some_value",
        prop_5: "some_value"
    }]
};

循环并推入新数组

我试图从obj获取一个名为new_arr的新数组作为输出结果,该数组仅填充prop_2prop_3以及key value }。如下面的示例结果:

new_arr = [ 
   ["some_value_2","some_value_3","key_1"],
   ["some_value_2","some_value_3","key_1"],
   ["some_value_2","some_value_3","key_2"],
   ["some_value_2","some_value_3","key_2"]
          ];

所以我尝试执行 for循环,在其中我只推送了所需的属性,如下面的示例代码:

    new_arr = [];

    for (var key in obj) {
       new_arr.push(
       obj[key][0].prop_2 + ', ' +  
       obj[key][0].prop_3 + ', ' + 
       key);
    }
    console.log(new_arr);

输出问题

困扰我的问题与new_arr仅包含[0]索引数组的事实有关。所以索引1处的数组不会被推入内部。有没有办法访问所有索引属性并为所有索引执行循环(不仅仅是案例索引[0])?

有什么建议吗? 谢谢你的建议!

2 个答案:

答案 0 :(得分:2)

使用嵌套循环。

var arr = {
    key_1: [{
        prop_1: "some_value",
        prop_2: "some_value_2",
        prop_3: "some_value_3",
        prop_4: "some_value",
        prop_5: "some_value"
    }, {
        prop_1: "some_value",
        prop_2: "some_value_2",
        prop_3: "some_value_3",
        prop_4: "some_value",
        prop_5: "some_value"
    }],
    key_2: [{
        prop_1: "some_value",
        prop_2: "some_value_2",
        prop_3: "some_value_3",
        prop_4: "some_value",
        prop_5: "some_value"
    }, {
        prop_1: "some_value",
        prop_2: "some_value_2",
        prop_3: "some_value_3",
        prop_4: "some_value",
        prop_5: "some_value"
    }]
};

var newarr = [];

for (var key in arr) {
    arr[key].forEach(obj => newarr.push([obj.prop_2, obj.prop_3, key]));
}

console.log(newarr);

请注意,根据您所需的输出,您推送的值应该是一个数组。值与逗号连接的字符串不是一回事。

arr[key].forEach(function)

arr[key]中遍历数组,在每个元素上调用函数,这些元素是数据中的嵌套对象。上面的函数创建了一个包含prop_2属性,prop_3属性和key的数组,并将其推送到new_arr数组。

修改后的场景,只需添加另一级嵌套for循环:

for (var key1 in obj) {
    for (var key2 in obj[key1]) {
        obj[[key1][key2].forEach(o => newarr.push([o.prop_2, o.prop_3, key1, key2]));
    }
}

答案 1 :(得分:1)

为索引

创建一个内部循环
for (var key in arr) {
for (var innerKey in arr[key]) {
   new_arr.push( [
   arr[key][innerKey].prop_2,  
   arr[key][innerKey].prop_3, 
   key ])
}
}