Use object array to generate a new array dynamically

前端 未结 3 2016
孤街浪徒
孤街浪徒 2021-01-16 14:45

I have a product form which I would like users to add variants of this product to. My object for the main settings

{
  title: \'Bike\',
  settings: {
    opt         


        
3条回答
  •  自闭症患者
    2021-01-16 15:44

    You could take the keys and values from data, generate the cartesian product from values and create key/value pairs as result.

    var data = { title: 'Bike', settings: { options: [{ title: 'Size', values: ['60cm', '80cm', '120cm'] }, { title: 'Color', values: ['White', 'Black', 'Red'] }], variants: [] } },
        keys = data.settings.options.map(({ title }) => title).concat('Image'),
        values = data.settings.options.map(({ values }) => values).concat([['img.png']]),
        cartesian = values
            .reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []))
            .map(a => Object.assign({ title: a.slice(0, -1).join('/') }, ...keys.map((k, i) => ({ [k]: a[i] }))));
    
    console.log(cartesian);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题