'create custom nested output from json using javascript
let data = {
"needData": [
{
arrayData: [
{
"key": "dummy",
"value": "needed value"
},
{
"key": "secret",
"random": "secret_random"
},
{
"key": "another",
"value": "testing"
},
{
"key": "another_Secret",
"random": "testing_value"
},
]
}
]
};
let json, testing;
data.needData.map((value) => {
json = {
arrayData: [
{
needed_key: value.arrayData[0].key,
needed_value: value.arrayData[0].value,
},
],
};
testing = {
arrayData: [
{
needed_key: value.arrayData.key,
needed_value: value.arrayData.value,
},
],
};
});
console.log("value got by running json", json);
console.log("value got by running testing", testing);
I am trying to save data in json object by using map function but the problem is I can save data by using needed_key:value.arrayData.key needed_value:value.arrayData.value
if all the needed_key and needed_value are same I can use above code but here problem is key name is same but the needed_value get change by random and value I only want to save values of those data which contain in value not random is there any way I can get key and value value not key and random value
I can use manual code to fetch the data but what if data is more and I don't want to use manual code
Expected Output
{
"arrayData": [
{
"needed_key": "dummy",
"needed_value": "needed value"
},
{
"needed_key": "another",
"needed_value": "testing"
}
]
}
Solution 1:[1]
Array.map and Array.filter implementation.
let data = {
"needData": [
{
arrayData: [
{ "key": "dummy", "value": "needed value" },
{ "key": "secret", "random": "secret_random" },
{ "key": "another", "value": "testing" },
{ "key": "another_Secret", "random": "testing_value" },
]
}
]
};
const output = data.needData.map((value) => {
const { arrayData } = value;
const opArrayData = arrayData.filter(item => item.key && item.value && !item.random);
const parsedArray = opArrayData.map((node => ({ needed_key: node.key, needed_value: node.value })));
return { arrayData: parsedArray }
});
console.log(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 | Nitheesh |
