简体   繁体   中英

Change structure of object JavaScript

I have object

const obj1 = {
app: {groups: [{name: 'test},{name: 'test2'}],
ap2: {groups: [{name: 'test1'},{name: 'test3'}],
}

How to change to this:

const obj1 = {
groups: [{name: 'test, type: 'app'},{name: 'test2', type: 'app'}, {name: 'test1, type: 'app2'},{name: 'test33', type: 'app2'}],
}

Assuming the typos in the original code, you could do something like that:

const obj1 = {
  app: {groups: [{name: 'test'},{name: 'test2'}]},
  app2: {groups: [{name: 'test1'},{name: 'test3'}]},
}

const obj2 = {
  groups: Object.entries(obj1).flatMap(([type, {groups}]) => 
    groups.map( ({name}) => ({name, type}) )
  )
}

console.log(obj2);

Not elegant, but readable;

 const obj1 = { app: { groups: [ {name: 'test'}, {name: 'test2'} ] }, ap2: { groups: [ {name: 'test1'}, {name: 'test3'} ], } } const obj2 = {}; obj2.groups = []; Object.keys(obj1).forEach( function(element) { obj1[element]['groups'].forEach( function(e) { var temp = {}; temp.name = e.name; temp.type = element; obj2.groups.push(temp) }); }); console.log(obj2);

var midObj = {name: '', type: ''};
var obj = {groups: []};
for(var I in obj1) {
  for(var j=0; j<obj1[I]['groups'].length; j++) {
    midObj = {};
    midObj.type = I;
    midObj.name = obj1[I]['groups'][j].name;
    obj['groups'].push(midObj);
  }
}

Assumptions: the source object define only as: const obj1 = { app: {groups: [{name: 'test},{name: 'test2'}], ap2: {groups: [{name: 'test1'},{name: 'test3'}], }

the solution works only for the mentioned source object. in order to do the same manipulation but with another source object it require to change the loops and their content

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