繁体   English   中英

angularjs将json对象转换为数组

[英]angularjs converting json object to array

嗨,我有这样的json返回对象

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

我如何将其转换为

color_selected = [4,3]

感谢您的帮助和建议

您可以像这样遍历它:

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

您可以使用javascript map功能

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

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

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]

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM