简体   繁体   English

从Javascript中的数组创建新的对象数组

[英]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. 我以为我需要一个loop函数来遍历数组,但是除了在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. 只需通过映射到目标格式来调整@chazsolo对预期输出的答案即可。

 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 使用slice获取您要查找的值

 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: 如果不使用map ,或者仍然不能使用map ,则仍然可以使用for循环:

 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 如果您想了解更多,请检查数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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