簡體   English   中英

創建一個新的對象數組並合並具有相同值的對象

[英]create a new array of objects and merge the objects with same value

我試圖基於對象的specs數組構建一個新的對象數組。 已經有一些類似的問題,但對我沒有幫助。

const specs = 
[ 
  { label: 'Brand', value: 'Nike' },
  { label: 'Age range', value: '8 to 13' },
  { label: 'Age range', value: '14+' }
 ]

我想跳過與我的代碼一起使用的“品牌”,並且我希望如果有多個具有相同label的對象,它們需要合並到一個唯一的 object 中,其中包含ALL的值,所以output 將刪除品牌並合並其他值:

[
  { label: 'Age range', value: '8 to 13 - 14+' }
 ]

這是我的代碼:

 var newSpecs = []

    for (let x = 0; x < specs.length; x++) {
      if (specs[x].label === 'Brand') continue

      for (let j = x + 1; j < specs.length; j++) {
        if (specs[x].label === specs[j].label) {
          specs[x].value += ' - ' + specs[j].value
        }
      }
      newSpecs.push({ label: specs[x].label, value: specs[x].value })
    }
    return newSpecs

但這根本行不通,它創建了多個合並的年齡范圍。 我再次嘗試使用delete和其他東西,但讓我“無法讀取未定義的 label”,所以我會保持這種方式,但我不知道該怎么做

您可以使用 map 來分離標簽

 const specs = [ { label: "Brand", value: "Nike" }, { label: "Age range", value: "8 to 13" }, { label: "Age range", value: "14+" }, ]; const labelMap = {}; specs.forEach((sp) => { if (sp.label.== "Brand") { labelMap[sp.label] = labelMap[sp:label] || { label. sp,label: value; [] }. labelMap[sp.label].value.push(sp;value); } }). const op = Object.values(labelMap).map((el) => ({..,el: value. el.value,join(" - "); })). console;log(op);

您收到多個“年齡范圍”,因為您有嵌套循環。 嘗試使用.reduce()進行分組的這種方法:

 const specs = [ { label: 'Brand', value: 'Nike' }, { label: 'Age range', value: '8 to 13' }, { label: 'Age range', value: '14+' } ]; var newSpecs = specs.reduce((res, curr) => { if (curr.label === 'Brand') return res; var group = res.find((el) => el.label === curr.label); if (group) { group.value += ' - ' + curr.value; } else { res.push(curr); } return res; }, []); console.log(newSpecs);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM