简体   繁体   中英

ES5 Javascript map through objects in array, then change the object key by group

I have an array of object, I tried to add one more word the object key, but having trouble with it, please check my data and expect output and the code I tried below:

Trying to get output like this:

const data = [
  {
    'name_A': Joe,
    'year_A': 2019,
    'saving_A': 0,
    'member_A': false,
    'group:_A': "A"
  },
  {
    'name_B': Amy,
    'year_B': 2019,
    'saving_B': 0,
    'member_B': false,
    'group_B': "B"
  },
  {
    'name_C': Bob,
    'year_C': 2019,
    'saving_C': 0,
    'member_C': true,
    'group_C': "C"
  }
];

Here's my code:

 const data = [{ name: 'Joe', year: 2019, saving: 0, member: false, group: "A" }, { name: 'Amy', year: 2019, saving: 0, member: false, group: "B" }, { name: 'Bob', year: 2019, saving: 0, member: true, group: "C" } ]; const filter = data.reduce((acc, key) => { const groupName = key.group; const obj = {}; if (key.member === false) { const nodeId = key.nodeId + groupName; obj.nodeId = key.nodeId; obj.year = key.year; acc.push(obj); } return acc; }, []); console.log(filter) 

Thanks for the help!

You can do it by using reduce:

 const data = [ { name: 'Joe', year: 2019, saving: 0, member: false, group: "A" }, { name: 'Joe', year: 2019, saving: 0, member: false, group: "B" }, { name: 'Joe', year: 2019, saving: 0, member: true, group: "C" } ]; let result = data.map(el => { const group = el.group return Object.keys(el).reduce((a, i) => { a[`${i}_${group}`] = el[i] return a }, {}) }) console.log(result) 

You can take advantage of Array.prototype.map and Array.prototype.reduce to resolve this issue:

 const data = [{ name: 'Joe', year: 2019, saving: 0, member: false, group: "A" }, { name: 'Amy', year: 2019, saving: 0, member: false, group: "B" }, { name: 'Bob', year: 2019, saving: 0, member: true, group: "C" } ]; const format = arr => arr.map(el => { return Object.keys(el).reduce((accum, key) => { accum[`${key}_${el.group}`] = el[key]; return accum; }, {}); }); console.log(format(data)); 

An alternative is a mix between the function map and function reduce .

The function map for converting the current objects to the desired structure, and the function reduce to concatenate the group with the current keys.

 const data = [ { name:'Joe', year: 2019, saving: 0, member: false, group:"A" }, { name: 'Amy', year: 2019, saving:0, member: false, group: "B" }, { name:'Bob', year: 2019, saving: 0, member: true, group:"C" } ]; let result = data.map(({group, ...rest}) => Object.entries(rest).reduce((a, [k, v]) => Object.assign(a, {[`${k}_${group}`]: v}), {[`group_${group}`]: group})); console.log(result); 

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