[英]transform array of objects in javascript
Im new in JS and I hope you help me) I need to transform array of objects in this way: 我是JS的新手,我希望你帮助我)我需要以这种方式转换对象数组:
const arr = [
{id: 'key1', value: 1 },
{id: 'key2', value: [1,2,3,4]}
...
]
const transformedArr = [
{key1: 1},
{key2: 1},
{key2: 2},
{key2: 3},
{key2: 4},
....
]
How can I do it? 我该怎么做?
Since you are new to JS .. 因为你是JS的新手..
Good Old JS with for loops might be easy for you to understand 带有for循环的Good Old JS可能很容易理解
const arr = [
{id: 'key1', value: 1 },
{id: 'key2', value: [1,2,3,4]}
]
const transformedArr =[]
for(var i = 0 ; i < (arr.length); i++){
var valArr = arr[i].value
if( Array.isArray(valArr) ){ // to check if the value part is an array
for(var j=0 ; j < valArr.length ; j++){
transformedArr.push({id: arr[i].id,value:valArr[j] })
}
}else{
transformedArr.push({id: arr[i].id,value:valArr })
}
}
console.log(transformedArr)
You can use ES6 spread syntax ...
with map()
method. 您可以使用ES6扩展语法...
使用map()
方法。
const arr = [ {id: 'key1', value: 1 }, {id: 'key2', value: [1,2,3,4]} ] var result = [].concat(...arr.map(({id, value}) => { return Array.isArray(value) ? value.map(e => ({[id]: e})) : {[id]: value} })) console.log(result)
You can also use reduce()
instead of map()
method. 您也可以使用reduce()
而不是map()
方法。
const arr = [ {id: 'key1', value: 1 }, {id: 'key2', value: [1,2,3,4]} ] var result = arr.reduce(function(r, {id, value}) { r = r.concat(Array.isArray(value) ? value.map(e => ({[id]: e})) : {[id]: value}) return r; }, []) console.log(result)
This proposal features Array.concat
, because it add items without array and arrays to an array. 此提议具有Array.concat
,因为它将没有数组和数组的项添加到数组中。
const array = [{ id: 'key1', value: 1 }, { id: 'key2', value: [1, 2, 3, 4] }], result = array.reduce( (r, a) => r.concat( [].concat(a.value).map( v => ({ [a.id]: v }) ) ), [] ); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.