我使用nodejs创建项目。我想的对象数组转换成简单array.For例如将对象数组转换为简单数组nodejs
var test = [ { id: '1111',
type: 'sdfsdf'
},
{ id: 'df45',
type: 'fsdsdf',
}]
我需要
var actual = [111,'sdfsdf'], ['df45','fsdsdf'].
我使用nodejs创建项目。我想的对象数组转换成简单array.For例如将对象数组转换为简单数组nodejs
var test = [ { id: '1111',
type: 'sdfsdf'
},
{ id: 'df45',
type: 'fsdsdf',
}]
我需要
var actual = [111,'sdfsdf'], ['df45','fsdsdf'].
我会提出了基于动态的数字键的此解决方案:
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
});
谢谢....这对我有用 – Karan
这可以通过使用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
接受任何对象并将其转换为数组,以便它可以灵活,而不管对象内的键。
只需使用'阵列#map' ... – Rayon
你能不能给我一个例子吗? – Karan
'test.map((el)=>([el.id,el.type]))' – Rayon