简体   繁体   English

使用单个键将javascript对象数组更改为包含对象数据的数组

[英]changing an array of javascript objects with a single key to an array that contains the objects' data

I currently have data in the following format: 我目前有以下格式的数据:

var anArray = [
  obj1: {
    key1: data1
  },
  obj2: {
    key2: data2
  },
];

I would like the data to instead be in the following format: 我希望数据改为采用以下格式:

var array2 = [data1, data2];

for some reason, I cannot figure out a concise way to to this. 由于某种原因,我无法找到一种简洁的方法。 I know it could be done with a forEach loop that iterates over each object and pushes it onto a new array, but I would prefer to be more elegant (and shorter if possible) than that. 我知道可以使用forEach循环来实现,该循环遍历每个对象并将其推入新数组,但是我希望比这更优雅(如果可能的话,更短)。

 const anArray = { obj1: { key1: "A" }, obj2: { key2: "B" }, }; const result = Object.keys(anArray).map(key => { const obj = anArray[key]; return Object.keys(obj).map(key => obj[key])[0]; }); console.log(result); 

Try with: 尝试:

 const arr1 = [ {key1:'value1'}, {key2:'value2'} ] const res = arr1.map(obj => { return Object.keys(obj).map(val => obj[val]) }).reduce((acc,v) => { return acc.concat(v); },[]); console.log(res); 

update 更新
But if you have the following form: 但是,如果您采用以下形式:

var anArray = [
  obj1: {
    key1: data1
  },
  obj2: {
    key2: data2
  },
];

It's better to apply a recursive function, as follow: 最好应用递归函数,如下所示:

 const arr1 = [ { obj1:{key1:'value1',key3:'value3'} }, { obj2:{key2:'value2'} } ] const getValuesFromObj = (obj) => { if(typeof obj === 'string') return obj; return Object.keys(obj).map(key => { return getValuesFromObj(obj[key]); }).reduce((acc,v) => { return acc.concat(v); },[]); } const r2 = getValuesFromObj(arr1); console.log(r2); 

Given that anArray is actually properly structured to be valid, then you could do the following: Note that in this case anArray isn't an actual array but rather a object literal 鉴于anArray实际上已经正确构造为有效,因此您可以执行以下操作:请注意,在这种情况下, anArray不是实际的数组,而是对象文字

var anArray = {
    obj1: {
        key1: "data1"
    },
    obj2: {
        key2: "data2"
    },
};

var array2 = []
for(i in anArray){
    for(j in anArray[i]){
        array2.push(anArray[i][j])
    }
}
console.log(array2)

https://jsfiddle.net/wh4r0w5s/ https://jsfiddle.net/wh4r0w5s/

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

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