Home > front end >  How to rearrange array of objects to new array of Objects
How to rearrange array of objects to new array of Objects

Time:12-23

I have an array of objects with the same keys, example:

const data = [{name: "firstName", value: "John"},
{name: "lastName", value: "Smith"},
{name: "Number", value: "421-8686"}
]

I however want the values to become the key and values. example:

const data = [{"firstName": "John"},
{"lastName": "Smith"},
{"Number": "421-8686"}]

I tried a few methods, but for some reason or another I fail. My latest attempt is:

   let newData = {}
    arrayData.forEach((item, index) => {
      let key = data.name
      let value = data.value
      newData[index] = { key: value} // this results in {"key": "John"} --> but i want {"firstName": "John"}

});

CodePudding user response:

const data = [{name: "firstName", value: "John"},
{name: "lastName", value: "Smith"},
{name: "Number", value: "421-8686"}
]


/*const data = [{"firstName": "John"},
{"lastName": "Smith"},
{"Number": "421-8686"}]
*/
for(let i = 0;i < data.length;i  ){
   
    data[i][data[i].name] = data[i].value  // creates new key value pair
    delete data[i].name                    // deletes old key
    delete data[i].value
    }
    

console.log(data)

CodePudding user response:

You can use Object.fromEntries.

let data = [
  {name: "firstName", value: "John"},
  {name: "lastName", value: "Smith"},
  {name: "Number", value: "421-8686"}
]

data = data.map(info => Object.fromEntries([[info.name, info.value]]))

console.log(data)

CodePudding user response:

    let data = [
       { name: "firstName", value: "John" },
       { name: "lastName", value: "Smith" },
       { name: "Number", value: "421-8686" },
    ];

    // map the data to required format.

    data = data.map((d) => {
       let o = {};
       o[d["name"]] = d["value"];
       return o;
    });
    
    console.log("data",data);
    
    

CodePudding user response:

I believe you should get result as following, what you want. Of course, I confirmed status.

const data = [{name: "firstName", value: "John"},
{name: "lastName", value: "Smith"},
{name: "Number", value: "421-8686"}
]

let newData = [];
data.forEach((item) => {
  let obj = {};
  obj[item.name] = item.value;
  newData.push( obj );
});
    
console.log(newData);

Thanks.

  • Related