ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Monday, December 19, 2022

[FIXED] How to compare and manipulate json object

 December 19, 2022     arrays, javascript, json, node.js, reactjs   

Issue

I need to compare and manipulate JSON objects.

First object

let data1 = {
  "id": "111",
  "entity_id": "222",
  "text_id": "333",
  "details": [{
    "value": 1000,
    "comp_id": "444",
    "CompName": "driving"
  }]
}

Second object

let data2 = [{
  "id": "111",
  "text_id": "333",
  "criteria_type": "TXT",
  "value": 1000,
  "comp": {
    "id": "444",
    "name": "driving"
  }
}, {
  "id": "222",
  "text_id": "444",
  "criteria_type": "TXT",
  "value": 2000,
  "comp": {
    "id": "555",
    "name": "swiming"
  }
}]

There are 2 objects data1 and data2. Here, I need to compare the data1.details array with the data2 array key => data1.details.comp_id with data2.comp.id if not match then I need to push value, id and name to data1 object. Please help me to resolve this issue.

Resulting object

data1 will be:

{
  "id": "111",
  "entity_id": "222",
  "text_id": "333", 
  "declaration_details": [{
    "value": 1000,
    "comp_id": "444",
    "CompName": "driving",
  }, {
    "value": 2000,
    "comp_id": "555",
    "CompName": "swiming",
  }]
}

Solution

Use filter() to find objects in the data2 matching comp.id. Then you can just use map() to create a new array. Finally, you can add the mappedData2 array to the data1 in declaration_details.

let filteredData2 = data2.filter(item => {
  return data1.details.some(detail => detail.comp_id === item.comp.id);
});
let mapData = filteredData2.map(item => {
  return {
    value: item.value,
    comp_id: item.comp.id,
    CompName: item.comp.name
  };
});


Answered By - Hannes Johan
Answer Checked By - - Dawn Plyler (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix