简体   繁体   中英

how to convert nested array of objects to object of array

I have got array of nested array of objects .

  const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]

I want to convert array to this format of objects and I want to get this output

 let permission ={

       group:["1"],
       topGroup:["2"]
     }

How can I do this ?

 const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ] const converted = data.reduce((a,b) => { const onlyKey = Object.keys(b)[0]; a[onlyKey] = b[onlyKey].map(i => i.label); return a; }, {}) console.log(converted)

 const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ] let permission = {}; data.forEach(val =>{ for(prop in val){ permission[prop] = [val[prop][0]["label"]] } }) console.log(permission)

Give this a upvote if this is what you want.

Assuming the data is going to have label s as in that format forever, you could use something like that

 const data = [{"group":[{"label":"1"}]},{"topGroup":[{"label":"12"}]}]; // The dict variable under here is the second parameter of reduce that I passed it `{}`. // The ind variable is the data at the index of the array. var newData = data.reduce(function(dict, ind){ // You basically get the keys and the values and put them in place // and return the last state to the reduce function. dict[Object.keys(ind)] = Object.values(ind)[0][0]["label"]; return dict; }, {}) console.log(newData)

Use destructuring and Object.fromEntries .

 const data = [{ group: [{ label: "1" }] }, { topGroup: [{ label: "2" }] }]; const permission = Object.fromEntries( data.map(item => { const [[key, [obj]]] = Object.entries(item); return [key, Object.values(obj)]; }) ); console.log(permission);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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