Home > Net >  how to pivot array javascript/react
how to pivot array javascript/react

Time:09-02

hello everyone hoping you are well, I have a question about how to convert an array in js

I have the following array:

[
{
id:1
L: 10,
XL: 20
},
{
id:2
L: 40,
XL: 50
}
]

and I need it to be like this:

[
{
id:1
name: L,
value: 10
},
{
id:1
name: XL,
value: 20
},
{
id:2
name: L,
value: 40
},
{
id:2
name: XL,
value: 50
}
]

Thanks for the help.

I am using react, so, any solution with js or react it will great.

CodePudding user response:

First, I did a foreach over the outer array. In there, I pulled the ID for the current object. Then, I took each entry in the object that wasn't "id", and split it into "name" and "value" as needed.

var first = [
    {id:1, L: 10, XL: 20},
    {id:2,L: 40,XL: 50}
];
let result = [];

first.forEach(id => {
    const currentId = id.id
    for (const [key, value] of Object.entries(id)) {
        if(key !== "id") {
            result.push({id: currentId, name: key, value: value})
        }
    }
})

CodePudding user response:

You can simply achieve this by using Array.forEach() along with Object.keys() method.

Live Demo :

const inputArr = [{
  id: 1,
  L: 10,
  XL: 20
}, {
  id: 2,
  L: 40,
  XL: 50
}];

const resultArr = [];

inputArr.forEach(obj => {
  Object.keys(obj).forEach(o => {
    if (o !== 'id') resultArr.push({ id: obj.id, name: o, value: obj[o] })
  })
});

console.log(resultArr);

CodePudding user response:

you can do this with following way

let a= [
        {
        id:1
        L: 10,
        XL: 20
        },
        {
        id:2
        L: 40,
        XL: 50
        }
    ]

    let res=[];
    a.forEach(t=>{
        res.push({
            id:t.id,
            name:'L',
            value:t.L
        })

        res.push({
            id:t.id,
            name:'XL',
            value:t.XL
        })

    })

    console.log("res",res)
  • Related