'Json Manipulation if json key having more than one fields
I have a json like this:
[
{
"objectid":"61b1",
"name":["abc","xyz"],
"date":["2021-08-20","2021-09-20"]
}
]
I want to manipulate the json to create a simple one as below:
[
{
"objectid":"61b1",
"name":"abc",
"date":"2021-08-20"
},
{
"objectid":"61b1",
"name":"xyz",
"date":"2021-09-20"
}
]
Please help if anyone has done this earlier. Thanks in advance.
Solution 1:[1]
You can use reduce to split date and name for each element and push the splite value to the accumulated result as follow:
var input = [
{
"objectid":"61b1",
"name":["abc","xyz"],
"date":["2021-08-20","2021-09-20"]
}
];
var output = input.reduce(function(acc, curr){
//foreach element we try to slipt it
// if we have more than one element in date or name
if(curr.name.length > 0 && curr.date.length > 0){
//we make sur that we the same length of date et name
var length = Math.min(curr.name.length, curr.date.length);
for(var i = 0; i < length; i ++){
var name = curr.name[i];
var date = curr.date[i];
acc.push({
"objectid": curr.objectid,
"name": name,
"date": date
});
}
}else{
acc.push(curr);
}
return acc;
},[])
output;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BETOMBO |
