Home > Net >  Loop array value into object javascript
Loop array value into object javascript

Time:01-25

i have problem with my javascript project. i have an array with value like this :

exmpArr = ["PX1","PX2","PX3"];

and i want to loop and push it to obj like this:

sections = [
            {
             rows: [
              { title: exmpArr[i], rowId: exmpArr[i] },
              ],
            },
           ];

the final value must like this:

sections = [
            {
             rows: [
              { title: "PX1", rowId: "PX1" },
              { title: "PX2", rowId: "PX2" },
              { title: "PX3", rowId: "PX3" },
              ],
            },
           ];

what should i do?

what i did is i put for loop inside the object and its not work

CodePudding user response:

map returns a new array from the one you're mapping over. So you can immediately assign that array as the property value when you build your object.

const exmpArr = ['PX1', 'PX2', 'PX3'];

const sections = [
  {
    rows: exmpArr.map(el => {
      return { title: el, rowId: el };
    })
  }
];

console.log(sections);

CodePudding user response:

const exmpArr = ['PX1', 'PX2', 'PX3'];
sections = []
rows = {}
for(let i=0; i< exmpArr.length;i  ){
     rows  = {"title": exmpArr[i],"rowId": exmpArr[i]};
     sections.push(rows);
};
console.log(sections);

CodePudding user response:

You can use the forEach method on the exmpArr array to iterate over the elements and push them to the sections object. Here's an example of how you can do this:

let exmpArr = ["PX1","PX2","PX3"];
let sections = [{rows: []}];
exmpArr.forEach(function(item) {
    sections[0].rows.push({title: item, rowId: item});
});
console.log(sections);

  • Related