Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

将json相同的值合并为数组

const product = {
    "id":2,
    ....
    "sku_list":[
        {
            "id":2,
            "price":77.76,
            "discount_price":null,
            "title":"金属灰·七龙珠",
            ....
            "specs":[
                {
                    "key_id":1,
                    "key":"颜色",
                    "value_id":45,
                    "value":"金属灰"
                },
                {
                    "key_id":4,
                    "key":"容量",
                    "value_id":14,
                    "value":"128G"
                }
            ],
            "code":"2$1-45#3-9#4-14",
            "stock":5
        },
        {
            "id":3,
            "price":77.76,
            "discount_price":null,
            "title":"金属银·七龙珠",
            ....
            "specs":[
                {
                    "key_id":1,
                    "key":"颜色",
                    "value_id":46,
                    "value":"银色"
                },
                {
                    "key_id":4,
                    "key":"容量",
                    "value_id":15,
                    "value":"256G"
                }
            ],
            "code":"2$1-45#3-9#4-14",
            "stock":5
        }
    ],
    "spu_img_list":[
        {
            "id":165,
            ....
        }
    ],
    "spu_detail_img_list":[
        {
            "id":24,
            ....
        }
    ],
    "sketch_spec_id":1,
    "default_sku_id":2
}

获取skuList中的specs,合并成类似如下结构:

{
    name: '颜色', //key
    id: '1',  //key_id
    list: ['金属灰', '银色'],  //value
  },
  {
    name: '容量', //key
    id: '4', //key_id
    list: ['128G', '256G'], //value
  },

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
395 views
Welcome To Ask or Share your Answers For Others

1 Answer

时间问题我只能写那么多了,暂时想不到最优解。


function mergeSpecs(skuList){
    let result = [];
    let specsData = [];
    skuList.forEach(v => {
        v.specs = v.specs||[];
        specsData = [...specsData,...v.specs];
    });
    specsData.forEach(v => {
        let cindex = result.findIndex(e => e.id === v.key_id);
        if(cindex === -1){
            result.push({
                id:v.key_id,
                name:v.key,
                list:[v.value]
            })
        }else{
            (!result[cindex]['list'].includes
(v.value))&&result[cindex]['list'].push(v.value);
        }
    });
    return result;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...