YOG_PHP
YOG_PHP

Reputation: 188

How to compare two json object, check if id is same then assign to another object value?

I have two objects

var JSON_Categories = '[{ "id" : "1", "text" : "Category A"}, { "id" : 2, "text" : "Category B" }]';
var JSON_Article = '[{ "id" : "1", "text" : "Article text A"}, { "id" : 3, "text" : "Article B"}]';
var categories = JSON.parse(JSON_Categories);
var article = JSON.parse(JSON_Article);

if id match for both JSON value then, I need to assign text category text value with an article text value.

it tried something like this, I know it's not a good solution can anyone help me on it?

var categoryValue = new Object();
categories.forEach(function(category) {
articles.forEach(article => {
    if (category.id === article.id) {
        categoryValue.id = category.id;
        categoryValue.text = article.text;
    } else {
        categoryValue.id = category.id;
        categoryValue.text = category.text;
    }
});
});

console.log('categoryValue', categoryValue);

       

Upvotes: 1

Views: 2050

Answers (1)

Rajneesh
Rajneesh

Reputation: 5318

You can map it and inside that find the Object from second array:

var JSON_Categories = JSON.parse('[{ "id" : "1", "text" : "Category A"}, { "id" : 2, "text" : "Category B" }]');
var JSON_Article = JSON.parse('[{ "id" : "1", "text" : "Article text A"}, { "id" : 3, "text" : "Article B"}]');

var result = JSON_Categories.map(({id, text})=>({id, text:JSON_Article.find(k=>k.id==id)?.text || text}));

console.log(result);

Upvotes: 1

Related Questions