简体   繁体   中英

Creating a new array of objects from an array in Javascript

So I feel like this should be easy, but I can't figure it out.

To simplify, I need to dynamically generate an array. Then I need my code to build a list of objects based off the middle of that array.

array = [a, b, c, d];
start = array[0];
finish = array[array.length - 1];
middle = [
  { middle: array[1] },
  { middle: array[2] }
] 

I need this to be dynamic, so I can't hardcode my middle values due to the array length not being set in stone. I assumed I needed a loop function to iterate through my array, but I've never used this for anything but creating a list in the DOM. I feel like I'm overthinking this or something, because this should be easy... everything I do breaks my code though.

my latest attempt was:

middle = [
  for (i = 1; i < array.length - 2; i++) {
    return { middle: array[i] };
  }
]

I think I get why it doesn't work. It just returns what I want, but I don't think that value ever gets stored.

Just adjusting @chazsolo's answer to your expected output with a mapping to your target format.

 const array = [1,2,3,4,5]; const middle = array.slice(1, -1).map(item => ({middle: item})); console.log(middle); 

Use slice to grab the values you're looking for

 const array = [1,2,3,4,5]; const middle = array.slice(1, -1); console.log(middle); 

This returns a new array containing every value except for the first and the last.


If you don't, or can't, use map , then you can still use a for loop:

 const array = [1,2,3,4,5]; const middle = array.slice(1, -1); for (let i = 0; i < middle.length; i++) { middle[i] = { middle: middle[i] }; } console.log(middle); 

Define an array and push whatever you want to push into it.

 let array = ['a', 'b', 'c', 'd'] let middles = [] for (i = 1; i < array.length - 1; i++) { middles.push({ middle: array[i] }) } console.log(middles) 

In case you want to learn more, check Array

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