简体   繁体   中英

Map value to key in array object

Hello I have a object array like below.

dataSource = [
      {
        NAME: "Jan",
        VALUE: 5,
        GRUP: "Grup 1"
      },
      {
        NAME: "Feb",
        VALUE: 15,
        GRUP: "Grup 1"
      },
      {
        NAME: "Mar",
        VALUE: 3,
        GRUP: "Grup 1"
      }
    ]

I want to map this to below expected output

[
 {
    Base:"Grup 1",
    Jan:5,
    Feb:15,
    Mar:3
 }
]

I tried

 let dataSource = [ { NAME: "Jan", VALUE: 5, GRUP: "Grup 1" }, { NAME: "Feb", VALUE: 15, GRUP: "Grup 1" }, { NAME: "Mar", VALUE: 3, GRUP: "Grup 1" } ] console.log(GetObject(dataSource)) function GetObject(arr){ return arr.map(el=> { let obj={}; obj[el.NAME]=el.VALUE; obj.BASE=el.GRUP return obj } ); }

but it doesn't give as expected result. It gives me three object array instead of multiple attributes in one object.

How can I map this?

Thanks in advance

Store the groups in an object:

const groups = {};

for (const data of dataSource) {
    if (!(data.GRUP in groups)) {
        groups[data.GRUP] = {Base: data.GRUP};
    }
    groups[data.GRUP][data.NAME] = data.VALUE;
}

const result = Object.values(groups);
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