将对象数组转换为简单数组nodejs

时间:2016-09-28 07:56:22

标签: javascript arrays node.js

我正在使用nodejs创建项目。我想将对象数组转换为简单数组。例如

var test =    [ { id: '1111',
        type: 'sdfsdf'
        },
      { id: 'df45',
        type: 'fsdsdf',
    }]

我需要

var actual = [111,'sdfsdf'], ['df45','fsdsdf'].

2 个答案:

答案 0 :(得分:2)

我会基于动态数量的密钥提出这个解决方案:

var arr = test.map(function(obj){
    return Object.keys(obj). // convert object to array of keys
         reduce(function(arr, current){arr.push(obj[current]); return arr}, []); // generate a new array based on object values 
});

答案 1 :(得分:0)

这可以使用Array.map()完成,如下所示:

var actual = []

test.map(function(object) {
    actual.push(objectToArray(object))
})

function objectToArray(obj) {
    var array = []

    // As georg suggested, this gets a list of the keys
    // of the object and sorts them, and adds them to an array
    var obj_keys = Object.keys(obj).sort()


    // here we iterate over the list of keys
    // and add the corresponding properties from the object
    // to the 'array' that will be returned        
    for(var i = 0; i < obj_keys.length; i++) {
        array.push(obj[obj_keys[i]])
    }
    return array
}

函数objectToArray接受任何对象并将其转换为数组,以便无论对象内的键是什么,它都可以灵活。

相关问题