多个 for 循环问题

我有两个数组键和子Grps。

使用这两个创建具有映射键到子Grps数组的新数组。


var keys = ["Subgroup", "0-3", "3-10", "11-40"];

var subGrps = ["SP_20k", "SP_40k", "SP_60k"];


var arrayOfObjects = [];


subGrps.forEach(function(id) {

  keys.forEach(function(item) {

    if (item === "Subgroup") {

      arrayOfObjects.push({

        [item]: id

      });

    } else {

      arrayOfObjects.push({

        [item]: ""

      });

    }

  });

});


console.log(arrayOfObjects);

预期输出:


  [{

    "Subgroup" : "SP_20k",

    "0-3": "",

    "3-10": "",

    "11-40": ""

  },

  {

    "Subgroup" : "SP_40k",

    "0-3": "",

    "3-10": "",

    "11-40": ""

  },

  {

    "Subgroup" : "SP_60k",

    "0-3": "",

    "3-10": "",

    "11-40": ""

  }]

forEach是好的选择吗?用于对 对象进行分组,并获取该输出。

我错过了什么来获得预期输出?

有人可以帮我吗?keys arraysubGrps array


慕慕森
浏览 105回答 5
5回答

aluckdog

您可以使用 Array.map 循环访问数组,创建一个将键设置为 from 值的对象,并使用 Object.assign 为数组中的其他条目添加空值:subGrpsSubgroupsubGrpskeysvar keys = ["Subgroup", "0-3", "3-10", "11-40"];var subGrps = ["SP_20k", "SP_40k", "SP_60k"];var arrayOfObjects = subGrps.map(v => Object.assign({    "Subgroup": v  },  ...keys.slice(1).map(k => ({    [k]: ""  }))));console.log(arrayOfObjects);展开代码段这可以简化为:var keys = ["Subgroup", "0-3", "3-10", "11-40"];var subGrps = ["SP_20k", "SP_40k", "SP_60k"];var arrayOfObjects = subGrps.map(v => Object.assign({},  ...keys.map(k => ({    [k]: k == 'Subgroup' ? v : ""  }))));console.log(arrayOfObjects);

皈依舞

您可以先创建对象,然后在循环中添加键。var keys = ["Subgroup", "0-3", "3-10", "11-40"];var subGrps = ["SP_20k", "SP_40k", "SP_60k"];// creates the object with keys once// you can also use foreach to create this keysObj too.var keysObj = keys.reduce((resObj, acc) => {  resObj[acc] = ''  return resObj}, {})// uses keysObj to generate array of objectsvar arrayOfObjects = subGrps.map(subGrp => ({...keysObj, Subgroup: subGrp}))console.log(arrayOfObjects)

翻过高山走不出你

如果你想特别对待它,我不知道为什么与其他键混在一起,但在这里你去:"Subgroup"const [sgKey, ...keys] = ["Subgroup", "0-3", "3-10", "11-40"];const subGrps = ["SP_20k", "SP_40k", "SP_60k"];const result = subGrps.map(sg => {  const obj = {    [sgKey]: sg  }  for (const k of keys) {    obj[k] = ''  }  return obj});console.log(result)

慕妹3146593

您需要执行以下操作:var keys = ["Subgroup", "0-3", "3-10", "11-40"];var subGrps = ["SP_20k", "SP_40k", "SP_60k"];var arrayOfObjects = [];subGrps.forEach(function(id) {  var obj = {}  keys.forEach(function(item) {    if (item === "Subgroup") {      obj[item]= id      arrayOfObjects.push(obj);    } else {      obj[item] = ""      arrayOfObjects.push(obj);    }  });});console.log(arrayOfObjects);

回首忆惘然

试试这个,const arr = [];subGrps.forEach(subGrp => {   const obj = {}   keys.forEach(key => obj[key] = (key === 'Subgroup') ? subGrp : '' );   arr.push(obj);})console.log(arr)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript