I have a common field in each JSON object, i.e Field A. And I have Variable fields depending on data from service, i.e,(Variable Field A and Variable Field B).
I have a JSON data in this below format:
[{
"Field A": "ABC",
"Variable Field A": "66"
},
{
"Field A": "DEF",
"Variable Field A": "70"
},
{
"Field A": "GHI",
"Variable Field A": "135"
},
{
"Field A": "JKL",
"Variable Field A": "19"
},
{
"Field A": "ABC",
"Variable Field B": "-729"
},
{
"Field A": "GHI",
"Variable Field B": "962"
},
{
"Field A": "DEF",
"Variable Field B": "334"
},
{
"Field A": "JKL",
"Variable Field B":"241"
}]
I need to put the variable fields together based on common field (here Field A), so that all variable fields for one common field is available within one object. How can I make my JSON converted to something like this?
[{
"Field A": "ABC",
"Variable Field A": "66",
"Variable Field B": "-729"
},
{
"Field A": "DEF",
"Variable Field A": "70",
"Variable Field B": "334"
},
{
"Field A": "GHI",
"Variable Field A": "135",
"Variable Field B": "962"
},
{
"Field A": "JKL",
"Variable Field A": "19",
"Variable Field B": "241
}]
Decode your json in the the proper datastructure and recreate your array of objects using the proper algorithm for the matching.
Something like:
If you're using javascript for that check .hasOwnProperty("propertyName") method that check if a field exists in the object. It should be usefull for checking if you have to get "Variable Field A" or "Variable Field B" from the object.
This is a great application for the Array reducer function. Try this:
const data = [] // your JSON data
data.reduce((acc,item)=>({
...acc,
[item['Field A']]: {...acc[item['Field A']],...item}
}),{})
The result:
{
ABC: {
'Field A': 'ABC',
'Variable Field A': '66',
'Variable Field B': '-729'
},
DEF: {
'Field A': 'DEF',
'Variable Field A': '70',
'Variable Field B': '334'
},
GHI: {
'Field A': 'GHI',
'Variable Field A': '135',
'Variable Field B': '962'
},
JKL: {
'Field A': 'JKL',
'Variable Field A': '19',
'Variable Field B': '241'
}
}
you can do something like this
const group = (data, field) => Object.values(data.reduce((res, item) => {
const existing = res[item[field]] || {}
return {
...res,
[item[field]]: {...existing, ...item}
}
}, {}))
const data = [{
"Field A": "ABC",
"Variable Field A": "66"
},
{
"Field A": "DEF",
"Variable Field A": "70"
},
{
"Field A": "GHI",
"Variable Field A": "135"
},
{
"Field A": "JKL",
"Variable Field A": "19"
},
{
"Field A": "ABC",
"Variable Field B": "-729"
},
{
"Field A": "GHI",
"Variable Field B": "962"
},
{
"Field A": "DEF",
"Variable Field B": "334"
},
{
"Field A": "JKL",
"Variable Field B":"241"
}]
const result = group(data, 'Field A')
console.log(result)