使用lodash来压缩嵌套的对象数组?

时间:2018-02-13 15:42:07

标签: javascript json lodash

我有一个json对象,我需要使用lodash转换为javascript:

{
    "BidNumber": 2,
    "BidResult": 1,
    "BidAmount": "6756",
    "BidData": [
        {
            "name": "JonSnow",
            "Data": "Standard data for Jon Snow"
        },
        {
            "LineNum": "HarryPotter",
            "Data": "Standard data for Jon Snow"
        },
        {
            "LineNum": "MickyMouse",
            "Data": "Standard data for Micky Mouse"
        }
    ],
    "BidReference": "22e06e66-e711-bd14-7874a-002219649f24"
} 

我想将其转换为:

{
    "bidNumber": 2,
    "bidResult": 1,
    "bidAmount": "6756",
    "bidData": {
        "jonSnow": "Standard data for Jon Snow",
        "harryPotter": "Standard data for Jon Snow",
        "mickyMouse": "Standard data for Micky Mouse"
    },
    "bidReference": "22e06e66-e711-bd14-7874a-002219649f24"
}

无法弄明白我在lodash中的表现(包括camelCase部分)

2 个答案:

答案 0 :(得分:2)

可以使用JS轻松完成..

data.BidData = Object.assign({}, ...data.BidData.map(el => { 
  return { [(el.name ? el.name : el.LineNum)]: el.Data } 
}));

除非您想使用_.extend

,否则您不需要使用loadash



var data = {
    "BidNumber": 2,
    "BidResult": 1,
    "BidAmount": "6756",
    "BidData": [
        {
            "name": "JonSnow",
            "Data": "Standard data for Jon Snow"
        },
        {
            "LineNum": "HarryPotter",
            "Data": "Standard data for Jon Snow"
        },
        {
            "LineNum": "MickyMouse",
            "Data": "Standard data for Micky Mouse"
        }
    ],
    "BidReference": "22e06e66-e711-bd14-7874a-002219649f24"
};

data.BidData = Object.assign({}, ...data.BidData.map(el => { 
  return { [jslcfirst(el.name ? el.name : el.LineNum)]: el.Data } 
}));

console.log(data);

function jslcfirst(string) 
{
    return string.charAt(0).toLowerCase() + string.slice(1);
}




答案 1 :(得分:0)

使用Lodash:

obj.BidData = _.reduce(obj.BidData, function(flatObj, item) {
    flatObj[_.camelCase(item.name || item.LineNum)] = item.Data;
    return flatObj;
},{});

但你不一定需要lodash(下划线),使用vanilla JS这很容易实现

function convertToCamelCase(string) {
    return string.charAt(0).toLowerCase() + string.slice(1);
}

obj.BidData = obj.BidData.reduce(function(flatObj, item) {
    flatObj[convertToCamelCase(item.name || item.LineNum)] = item.Data;
    return flatObj;
},{})