简体   繁体   English

如何根据key id合并Json对象?

[英]How to merge Json object on the basis of key id?

I have a json like that.我有一个这样的json。 Now I want to merge it on the basis of articleId.现在我想在articleId的基础上合并它。

                   [{
                        "articleId": "45",
                        "isA": false,
                        "flags": {
                            "isDema": false,
                            "isCont": true,
                        },
                        "Proc": [
                            {
                                "level1": "tt",
                                "description": "I am well"
                            }
                        ],
                        "isAlert": false
                    },
                    {
                        "articleId": "46",
                        "isA": false,
                        "flags": {
                            "isDema": false,
                            "isCont": true,
                        },
                        "Proc": [
                            {
                                "level1": "ty",
                                "description": "I am fine"
                            }
                        ],
                        "isAlert": false
                    },
                    {
                        "articleId": "45",
                        "isA": false,
                        "flags": {
                            "isDema": false,
                            "isCont": true,
                        },
                        "Proc": [
                            {
                                "level1": "tt",
                                "description": "I am beautiful"
                            }
                        ],
                        "isAlert": false
                    }];

We see here article id 45 is two time although description field is different.我们在这里看到文章 id 45 是两次,尽管描述字段不同。 SO I want to add description in one array.所以我想在一个数组中添加描述。 After merge it I want to get a output like that.合并后我想得到这样的输出。

[{
                        "articleId": "45",
                        "isA": false,
                        "flags": {
                            "isDema": false,
                            "isCont": true,
                        },
                        "Proc": [
                            {
                                "level1": "tt",
                                "description":[
                                             "I am well",
                                             "I am beautiful"
                                           ]
                            }
                        ],
                        "isAlert": false
                    },
                    {
                        "articleId": "46",
                        "isA": false,
                        "flags": {
                            "isDema": false,
                            "isCont": true,
                        },
                        "Proc": [
                            {
                                "level1": "ty",
                                "description": "I am fine"
                            }
                        ],
                        "isAlert": false
                    }];

I am trying it direct string parse.我正在尝试直接字符串解析。 Is there any other way ?还有其他方法吗? By the way I am using node js.顺便说一下,我正在使用节点 js。 Is there any built in method that can merge two json object ?是否有任何内置方法可以合并两个 json 对象?

You probably have to write your own merge function - something like this:您可能必须编写自己的合并函数 - 如下所示:

var json = [{
    "articleId": "45",
    "isA": false,
    "flags": {
        "isDema": false,
        "isCont": true,
    },
    "Proc": [{
        "level1": "tt",
        "description": "I am well"
    }],
    "isAlert": false
}, {
    "articleId": "46",
    "isA": false,
    "flags": {
        "isDema": false,
        "isCont": true,
    },
    "Proc": [{
        "level1": "ty",
        "description": "I am fine"
    }],
    "isAlert": false
}, {
    "articleId": "45",
    "isA": false,
    "flags": {
        "isDema": false,
        "isCont": true,
    },
    "Proc": [{
        "level1": "tt",
        "description": "I am beautiful"
    }],
    "isAlert": false
}];

const merged = json.reduce((acc,item)=>{
    const found = acc.find(article=>article.articleId === item.articleId)
    if (!found) {
        acc.push(item)
    } else if (found.Proc[0].description !== item.Proc[0].description) {
        found.Proc[0].description = [found.Proc[0].description, item.Proc[0].description]
    }
    return acc;
}
, [])

console.log(merged)

However, this example assumes you never have more than 1 item in Proc , so you have to deal with that.然而,这个例子假设你在Proc永远不会有超过 1 个项目,所以你必须处理它。 Also if some other keys differ when merging, you have to write logic how to deal with those.此外,如果合并时其他一些键不同,您必须编写逻辑来处理这些。 What if "isA" is different?如果“isA”不同呢? would it end up being "isA": [false, true] ?它最终会成为"isA": [false, true]吗?

In the end, it's a bad practice to change datatype, from string to array of strings after merging.最后,在合并后将数据类型从字符串更改为字符串数组是一种不好的做法。 This will lead to spaghetti code eventually这最终将导致意大利面条式代码

So you want to eliminate duplicates based on the child object articleId.因此,您希望根据子对象 articleId 消除重复项。 Now suppose you have stored your initial array inside variable data.现在假设您已将初始数组存储在变量数据中。

This might solve your problem.这可能会解决您的问题。

let articleIdSet = new Set();
let newData = [];
data.map((item) => {
    const { articleId }= item;
    if(articleIdSet.has(articleId)) return; // return if the id is already present
    else {
      articleIdSet.add(articleId); // else add new id into the set
      newData.push(item);          // and push the item into new array
    }
})

Now newData would contain non-duplicate items.现在 newData 将包含非重复项。

Try for the following:尝试以下操作:

 var arr = [{ "articleId": "45", "isA": false, "flags": { "isDema": false, "isCont": true, }, "Proc": [{ "level1": "tt", "description": "I am well" }], "isAlert": false }, { "articleId": "46", "isA": false, "flags": { "isDema": false, "isCont": true, }, "Proc": [{ "level1": "ty", "description": "I am fine" }], "isAlert": false }, { "articleId": "45", "isA": false, "flags": { "isDema": false, "isCont": true, }, "Proc": [{ "level1": "tt", "description": "I am beautiful" }], "isAlert": false } ]; var fianlArr = []; arr.map(function(element) { var filterArr = fianlArr.filter(finalArrEle => finalArrEle.articleId === element.articleId); if (filterArr.length) { var proc = []; var desc = []; var obj = {}; obj.level1 = element.Proc[0].level1; desc.push(filterArr[0].Proc[0].description); desc.push(element.Proc[0].description); obj.description = desc; proc.push(obj); fianlArr[fianlArr.indexOf(filterArr[0])].Proc = proc; } else { fianlArr.push(element); } }) console.log("fianlArr", fianlArr)

The JSON structure the above should have always the same structure.上面的JSON结构应该始终具有相同的结构。

Group by articleId using a map where key is the articleId:使用地图按文章 ID 分组,其中键是文章 ID:

const source = [{"articleId":"45","isA":false,"flags":{"isDema":false,"isCont":true},"Proc":[{"level1":"tt","description":"I am well"}],"isAlert":false},{"articleId":"46","isA":false,"flags":{"isDema":false,"isCont":true},"Proc":[{"level1":"ty","description":"I am fine"}],"isAlert":false},{"articleId":"45","isA":false,"flags":{"isDema":false,"isCont":true},"Proc":[{"level1":"tt","description":"I am beautiful"}],"isAlert":false}];

const bucket = {}
source.map((item) => {
    const merged = bucket[item.articleId];
    if (!merged) {
        item.Proc[0].description = [item.Proc[0].description]
        bucket[item.articleId] = item;
        return;
    }
    merged.Proc[0].description.push(item.Proc[0].description)
});

const out = [];
for (const key in bucket) {
    const val = bucket[key];
    if (val.Proc[0].description.length === 1) {
        val.Proc[0].description = val.Proc[0].description.pop();
    }
    out.push(val);
}

console.log(JSON.stringify(out));

 var before = [{ "articleId": "45", "isA": false, "flags": { "isDema": false, "isCont": true, }, "Proc": [ { "level1": "tt", "description": "I am well" } ], "isAlert": false }, { "articleId": "46", "isA": false, "flags": { "isDema": false, "isCont": true, }, "Proc": [ { "level1": "ty", "description": "I am fine" } ], "isAlert": false }, { "articleId": "45", "isA": false, "flags": { "isDema": false, "isCont": true, }, "Proc": [ { "level1": "tt", "description": "I am beautiful" } ], "isAlert": false }]; var articles = []; let results = []; before.forEach((item) => { if (!articles.includes(item.articleId)) { articles.push(item.articleId); var obj = { "articleId": item.articleId, "isA": item.isA, "flags": { "isDema": item.flags.isDema, "isCont": item.flags.isCont, }, "Proc": [ { "level1": item.Proc.level1, "description": [item.Proc[0].description] } ], "isAlert": false } results.push(obj); } else { var index = articles.indexOf(item.articleId); results[index].Proc[0].description.push(item.Proc[0].description); } }) console.log(JSON.stringify(results));

The above solution is an answer to your solution.上述解决方案是您的解决方案的答案。 But I'd rather if you make the Proc just an object because it doesn't have more than one object in it.但我更愿意让 Proc 只是一个对象,因为它里面只有一个对象。 If it has more than one objects in different situations let me know I'll improve this answer.如果它在不同情况下有多个对象,请告诉我我会改进这个答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM