簡體   English   中英

Javascript:在JavaScript中從另一個對象創建一個深度嵌套的對象

[英]Javascript: create a deeply nested object in javascript from another object

Javascript:如何從對象數組動態創建深層嵌套的對象? 我可以實現一個級別的分離,但是代碼變得相當復雜,無法找出如何實現第二個級別的分離。

實際:

[{
    brandId: 1,
    spec_desc: "engines",
    av: 3000
    tv: 1000,
    brandName: "bmw",
    id: 1,
    group: "cars",
    cost: 20000.00,
    currency: "USD",
    desc: "manufacturing costs"
  },
  {
    brandId: 1,
    spec_desc: "brakes",
    av: 1000,
    tv: 2000,
    brandName: "bmw",
    id: 1,
    ....
  },
  {
    brandId: 2,
    spec_desc: "engines",
    av: 1800,
    tv: 2500,
    brandName: "audi",
    id: 2
    ....
  }
]

預期:

[{
    group: "cars",
    id: 1,
    brands: [{
        brandId: 1,
        brandName: "BMW",
        specs: {
          power: [{
              spec_desc: "engines",
              av: 3000,
              tv: 1000
            },
            {
              spec_desc: "brakes",
              av: 1000,
              tv: 2000
            }
          ],
          cost: {
            desc: "manufacturing costs",
            value: 20000.00,
            currency: "USD"
          }
        }
      },
      {
        brandId: 2,
        brandName: "audi",
        specs: {
          power: [
            ...
          ],
        }
      }
    ]
  },
  group: "bikes",
  id: 2,
  brands: [
    ....
  ]
]

這是我嘗試過的方法,但是只能獲得直到brandName即一個級別的分組。

function genrows(groups, groupKey) {
  return _.toPairs(groups).map(([key, units]) => ({
    [groupKey]: key,
    units
  }))
}

function gengroups(arr, iteratee, key) {
  const grouped = _.groupBy(arr, iteratee)
  return genrows(grouped, key)
}

function grouparray(units, props) {
  let result = [{
    units
  }]
  props.forEach((prop, i) => {
    const key = prop
    const iteratee = prop.iteratee || prop
    result = _.flatten(
      result.map(row => {
        return gengroups(row.units, iteratee, key).map(group =>
          // {...row, ...{ [key]: group[key], units: group.units }}
          ({ ...row,
            [key]: group[key],
            units: group.units
          }),
        )
      }),
    )
  })
  return _.flatten(result)
}

const groups = ['brandName', 'id'] //group by key names
// it fetches out these group tags to generate keys, 
const desired = grouparray(actual, groups);

誰能幫助我解決如何動態實現這一目標? 如果您已經做到了這一點,非常感謝您花時間閱讀,即使您不能幫助。

PS:讓我知道進一步的澄清,我的結果對象也使用了lodash函數。

您可以采用經典的方法,即存儲最后一個找到id組,然后使用此對象將品牌分組。

 var data = [{ brandId: 1, spec_desc: "engines", av: 3000, tv: 1000, brandName: "bmw", id: 1, group: "cars", cost: 20000.00, currency: "USD", desc: "manufacturing costs" }, { brandId: 1, spec_desc: "brakes", av: 1000, tv: 2000, brandName: "bmw" }, { brandId: 2, spec_desc: "engines", av: 1800, tv: 2500, brandName: "audi" }], lastGroup, result = data.reduce((r, { brandId, spec_desc, av, tv, brandName, id, group, cost: value, currency, desc }) => { if (id !== undefined) r.push(lastGroup = { group, id, brands: [] }); var brand = lastGroup.brands.find(q => q.brandId === brandId); if (!brand) lastGroup.brands.push(brand = { brandId, brandName, specs: { power: [], cost: { desc, value, currency } } }); brand.specs.power.push({ spec_desc, av, tv }); return r; }, []); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

暫無
暫無

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

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