简体   繁体   中英

How can I extract innermost value from an array of nested JSON data using their keys?

The following data structure is an array and each array element being an object with keys:

this.objectImWorkingWith = [
  {
    "1306": {
      "id": 6460,
      "data": "Process",
    },
    "1307": {
      "id": 6461,
      "data": "1287",
    },
    "1309”: {
      "id": 6462,
      "data": “2748”,
    }
  },
  {
    "1306": {
      "id": 6465,
      "data": "Product",
    },
    "1307": {
      "id": 6466,
      "data": "2574",
    },
    "1309”: {
      "id": 6263,
      "data": “3752”,
    }
  },
  {
    "1306": {
      "id": 6470,
      "data": "Research",
    },
    "1307": {
      "id": 6471,
      "data": "3861",
    },
    "1307": {
      "id": 6472,
      "data": “2248”,
    }
  }
]

Each element within the array has multiple objects within it and I want to retrieve the value of 'data' for each object within the parent object whilst retaining the structure. Meaning that I want to keep, for example, Process, 1287 and 2748 grouped together and so on.

So in summary I am aiming to get the value of "data" for each object within the array but keep all values of data that are in the same object in the array associated to each other.

I've tried

Object(this.allRelevantData.map(a=>a.data))

however it yields

[undefined, undefined, undefined]

You could try this:

var objectImWorkingWith = [
  {
    1306: {
      id: 6460,
      data: "Process",
    },
    1307: {
      id: 6461,
      data: "1287",
    },
    1309: {
      id: 6462,
      data: "2748",
    },
  },
  {
    1306: {
      id: 6465,
      data: "Product",
    },
    1307: {
      id: 6466,
      data: "2574",
    },
    1309: {
      id: 6263,
      data: "3752",
    },
  },
  {
    1306: {
      id: 6470,
      data: "Research",
    },
    1307: {
      id: 6471,
      data: "3861",
    },
    1307: {
      id: 6472,
      data: "2248",
    },
  },
];

const result = objectImWorkingWith.map((object) => {
  const data = [];
  for (var key of Object.keys(object)) {
    data.push(object[key].data);
  }

  return data;
});

variable result will contain: [["Process", "1287", "2748"], ["Product", "2574", "3752"],...]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM