angularjs将json对象转换为数组

时间:2017-05-12 17:14:35

标签: javascript arrays json object

嗨我有这样的json返回对象

color_selected = [
                { id: 4}, 
                { id: 3} 
    ];

如何将其转换为

color_selected = [4,3]

感谢您的任何帮助和建议

4 个答案:

答案 0 :(得分:3)

您可以像这样迭代它:

var newArray = [];
for(var i = 0; i < color_selected.length; i++) {
    newArray.push(color_selected[i].id);
}

答案 1 :(得分:2)

您可以使用javascript map函数

var newArray = color_selected.map(o=> o.id)

&#13;
&#13;
var color_selected = [
                { id: 4}, 
                { id: 3} 
    ];
 var newArray = color_selected.map(o=> o.id)
 console.log(newArray)
&#13;
&#13;
&#13;

答案 2 :(得分:1)

color_selected = [
            { id: 4}, 
            { id: 3} 
];

你可以使用lodash

// 3.10.1

_.pluck(color_selected, 'id'); // → [4, 3]
_.map(color_selected, 'id'); // → [4, 3]

// 4.0.0

_.map(color_selected, 'id'); // → [4, 3]

答案 3 :(得分:0)

Array.map()方法与ES6箭头运算符一起使用。

var color_selected = [
                { id: 4}, 
                { id: 3} 
    ];
    
color_selected = color_selected.map(item => {return item.id });

console.log(color_selected);