Input-
{
"0": {
"NAME": "ABC"
},
"1": {
"NAME": "DEF"
},
"2": {
"NAME": "GHI"
},
"3": {
"NAME": "JKL"
},
"4": {
"NAME": "MNO"
}
}
我有这个输入。我想只获得数组格式的名称,如输出 -
["ABC", "DEF", "GHI", "JKL", "MNO"].
试
var arr =[]; for( var i in data ) { if (data.hasOwnProperty(i)){ arr.push(data[i]); } }
答案 0 :(得分:2)
遍历object
的键并将其NAME
属性映射到数组中。
var input = { "0": { "NAME": "ABC" }, "1": { "NAME": "DEF" }, "2": { "NAME": "GHI" }, "3": { "NAME": "JKL" }, "4": { "NAME": "MNO" } };
var result = Object.keys(input).map(function(key){
return input[key].NAME;
});
console.log(result);
答案 1 :(得分:1)
你必须循环遍历对象并获取值。
var data={0:{NAME:"ABC"},1:{NAME:"DEF"},2:{NAME:"GHI"},3:{NAME:"JKL"},4:{NAME:"MNO"}};
var result = Object.keys(data).map(x=>data[x].NAME)
console.log(result)

var data={0:{NAME:"ABC"},1:{NAME:"DEF"},2:{NAME:"GHI"},3:{NAME:"JKL"},4:{NAME:"MNO"}};
var result = [];
for(var key in data){
result.push(data[key].NAME)
}
console.log(result)

答案 2 :(得分:0)
因为键是数字键,或者可以很容易地转换为数字,所以如果添加长度属性,则可以使用内置数组迭代方法。然后,您可以使用reduce方法构建数组。
以下是ES6示例:
const input={0:{NAME:"ABC"},1:{NAME:"DEF"},2:{NAME:"GHI"},3:{NAME:"JKL"},4:{NAME:"MNO"}};
input.length = Object.keys(input).length;
const result = Array.prototype.reduce.call(input,
(output, element, index) => ((output[+index] = element.NAME), output), []);
console.log(result); // ["ABC", "DEF", "GHI", "JKL", "MNO"]

答案 3 :(得分:-2)
var result={0:{NAME:"name1"},1:{NAME:"name2"},2:{NAME:"name3"}};
var array = [];
for(var i=0; i<=result.length-1; i++){
array.push(result[i].NAME);
}
console.log(array)