Skip to content
Advertisement

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"
      }
  ]
}

Advertisement

Answer

This gives your output:

var output = {
  'arrayData': data.needData[0].arrayData
    .filter(x => !Object.keys(x).includes('random'))
    .map(x => {
      return {needed_key: x['key'], needed_value: x['value']}
    })
}
console.log(output);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement