1

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.

4
  • Does this answer your question? How to pivot a javascript array Commented Sep 1, 2022 at 21:51
  • hi, sorry for that, it updated the question. Commented Sep 1, 2022 at 21:53
  • I don't mean to nitpick, but id:1 needs a comma after it. Should help anyone doing a copy/paste to help solve. Commented Sep 1, 2022 at 21:57
  • jsfiddle.net/3640ym8b - That'll be $30 Commented Sep 1, 2022 at 22:01

3 Answers 3

1

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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})
        }
    }
})

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.