像这样修改数组的循环会是什么样子?

What would the loop look like to modify an array like this?

javascript 中是否有一种方法可以循环访问作为对象数组一部分的对象中特定键的每个值,然后使用不同的键为每个值创建一个新项?请允许我用代码来解释我想在这里完成什么。

这是我的:

const x = [{
  name: 'name1',
  value: ['value1', 'value2', 'value3']
}, {
  name: 'name2',
  value: ['value4', 'value5', 'value6']
}]

这应该是新的结果:

const y = [{
  'name1': 'value1',
  'name2': 'value4',
}, {
  'name1': 'value2',
  'name2': 'value5',
}, {
  'name1': 'value3',
  'name2': 'value6',
}]

任何帮助将不胜感激!

以下是我目前尝试过的方法。 (它有效,但我很确定有更简单的方法)。

const y = [];
const z = [];
const xLength = x.length

for (let i = 0; i < xLength; i++) {
  x[i].value.forEach((item, index) => {
    z[index] = z[index] || [];
    z[index].push(x[i].name, item);
  });
}
z.forEach((items, index) => {
  const obj = {};

  items.forEach((item, k) => {
    if (k % 2) {
      obj[items[k - 1]] = item;
    } else {
      obj[item] = null;
    }
  });

  y.push(obj);
});

我相信这应该有效:

//start with array to store the answer
let y = []

//Next iterate threw each object in your 'x' array passing in to the callback xObj which is each object in your x array
x.forEach((xObj)=> {
  //store the name value just to make it easier to read
  let name = xObj.name

  //iterate through the values in each xObj, getting the 'value' and the index
  xObj.value.forEach((value, index)=>{
    
    //check if the y array has anything at the same index, if not create a blank object
    if(!y[index]) y[index]= {}

    //put in that object a key:value with the 'name' and 'value'
    y[index][name] = value 
    })
})