简体   繁体   中英

How can we modify javascript array to array object?

I have this array arr = [{id:1},{id:2},{id:3},{id:5},{id:5}] I want to modify array like index 0 - 1 is first, 2 -3 is second, 4 - 5 is third and so on

Result array: [first:[{id:1},{id:2}],second:[{id:3},{id:5}],third:[{id:5}]]

How can I modify array in such type?

The result you are expecting is not a valid array.

[first: [{},{}]]

It should be either an array like this

[[{},{}],[{},{}]]

or an object

{"first":[{},{}],"second":[{},{}]}

The code below converts your input to an array, it can be easily modified to an object if that's what you are looking for with some small modifications.

const arr = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 5 }, { id: 5 }];
let result = arr.reduce((acc, current, index) => {
  if (index % 2 == 0) {
    acc.push([current]);
  } else {
    acc[Math.floor(index / 2)].push(current);
  }
  return acc;
}, []);

You can use array.prototype.map . This example returns the id value of each multiplied by the number it exists in the array.

let arr = [{id:1},{id:2},{id:3},{id:5},{id:5}];
arr.map(function(item,index) {
    return item.id * index;
})

Try it out!

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