使用 javascript 从 json 创建自定义嵌套输出

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);

我正在尝试使用映射函数将数据保存在 json 对象中,但问题是我可以使用 needed_key:value.arrayData.key needed_value:value.arrayData.value

保存数据

如果所有 needed_key 和 needed_value 都相同我可以使用上面的代码但这里的问题是键名相同但是 needed_value 被 random and value 改变我只想保存包含在 value 而不是 random 中的那些数据的值 有什么办法可以获得 key and value 值而不是 key and random

我可以使用手动代码来获取数据,但如果数据更多并且我不想使用手动代码怎么办

预期输出

{
  "arrayData": [
      {
          "needed_key": "dummy",
          "needed_value": "needed value"
      },
      {
          "needed_key": "another",
          "needed_value": "testing"
      }
  ]
}

这给出了你的输出:

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);

Array.mapArray.filter 实施。

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);