Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through an array of objects and create a new object

Tags:

javascript

I have an array of objects, each object has a title, content and contentHTML. I want to map over this array and create a new object. The new object will take the value of the title property and use this as the parent property for each of the content and contentHTML properties. The code below only seems to be getting the last object in the array.

The results is:

{
  "sidebar": {
      "text": "Some sidbar text here",
      "content": "<p>Some sidebar text here</p>"
    }
}

The expected result is:

{
    header: {
        text: "Some header text here",
        content: "<p>Some header text here</p>"
    },
    footer: {
        text: "Some footer text here",
        content: "<p>Some footer text here</p>"
    },
    sidebar: {
        text: "Some sidbar text here",
        content: "<p>Some sidebar text here</p>"
    }
}

var originalObj = [{
    title: "header",
    content: "Some header text here",
    contentHTML: "<p>Some header text here</p>"
  },
  {
    title: "footer",
    content: "Some footer text here",
    contentHTML: "<p>Some footer text here</p>"
  },
  {
    title: "sidebar",
    content: "Some sidbar text here",
    contentHTML: "<p>Some sidebar text here</p>"
  }
];
let newObject = {};
for (let item of originalObj) {
  var tempObj = {
    [item.title]: {
      text: item.content,
      content: item.contentHTML
    }
  };
  newObject = tempObj;
}
console.log(newObject);
like image 500
user3486427 Avatar asked Jul 28 '26 06:07

user3486427


1 Answers

You are overwriting your object with new value every time you're doing

var tempObj = {//object keys}

Use spread operator to copy the previous values. Spread operator loops through objects iterable values and expands them.

var originalObj = [
    {
        title: "header",
        content: "Some header text here",
        contentHTML: "<p>Some header text here</p>"
    },
    {
        title: "footer",
        content: "Some footer text here",
        contentHTML: "<p>Some footer text here</p>"
    },
    {
        title: "sidebar",
        content: "Some sidbar text here",
        contentHTML: "<p>Some sidebar text here</p>"
    }
];

let newObject = {};
for (let item of originalObj) {
    newObject = {
        ...newObject,
        [item.title]: {
            text: item.content,
            content: item.contentHTML
        }
    };
}
console.log(newObject);
like image 87
Anurag Awasthi Avatar answered Jul 29 '26 19:07

Anurag Awasthi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!