从JS中的对象获取数组

时间:2017-01-31 06:00:04

标签: javascript jquery

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]); } } 

4 个答案:

答案 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)

你必须循环遍历对象并获取值。

Object.keys + Array.map



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)




的for..in



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)