简体   繁体   中英

How to create a list of objects in JavaScript

I have an array of pairs of values somewhat like this:

 let myarr = [[1, 'a'],
              [2, 'b'],
              [3, 'c']] 

and one like this:

let otherArr = [5,6,7]

and I would like to convert them to an object which would be of the form:

{
   "data":[
      {
         "id":5,
         "pair":[
            1,
            "a"
         ]
      },
      {
         "id":6,
         "pair":[
            2,
            "b"
         ]
      },
      {
         "id":7,
         "pair":[
            3,
            "c"
         ]
      }
   ]
}

As a first attempt

I tried to use a for loop and tried to create a list of the pair keys like this

for (let pair = 0; pair < myarr.length; pair++) {
  myobj[pair].pair = myarr[pair]

and I get an error stating TypeError: Cannot set property 'pair' of undefined

Is there a efficient way to create a object like the example above Thanks in advance

The reason your for loop fails is because you need to instantiate an object before you can set properties on it. For example, you could use Array.push to iterate over your array and create new objects at each index.

const myobj = { data: [] };
for (let index = 0; index < myarr.length; index++) {
    myobj.data.push({ pair: myarr[index], id: otherArr[index]})
}

A shorter way to write the above, assuming that myarra and otherArr will always have the same length, would be to use Array.map to iterate over your first array and return a new one of the same length.

const myobj = { data: myArra.map((pair, index) => ({ pair, id: otherArr[index] }) }

Try this :

 let otherArr = [5,6,7]; let myarr = [[1, 'a'], [2, 'b'], [3, 'c']]; let obj = { "data":[] }; otherArr.map((item, index) => { obj.data.push({ "id": item, "pair": myarr[index] }) }); console.log(obj);

You can do something like below

 let myarr = [[1, 'a'], [2, 'b'], [3, 'c']]; let otherArr = [5,6,7]; let data = myarr.map((i,idx) => { return { "id": otherArr[idx], "pair": i }; }); console.log({data});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM