0

I have this json

$ cat a.json
{
  "students": [
    {
      "name": "jack",
      "id": "0012"
    },
    {
      "name": "tom",
      "id": "0023"
    }
  ]
}

I'd like to generate two variables, such as

names = ["jack", "tom"];
ids=["0012", "0023"];

They are one to one mapped between names and ids

I read this, but it only works on maps, but my json is nested JSON. how can I get the result?

// this doesn't work with my sample.
let keys = Array.from( myMap.keys() )
Bill
  • 2,494
  • 5
  • 26
  • 61

1 Answers1

1

I'm assuming you have same nesting level. Then this solution will work. If you have different nesting levels to find name and id let me know I will update the code.

let name=[];
let ids=[];
let data = {
  "students": [
    {
      "name": "jack",
      "id": "0012"
    }, {
      "name": "tom",
      "id": "0023"
    }
  ]
};

data.students.map((val, key, ref) => {
 name.push(val.name);
 ids.push(val.id);
});

document.write(`Name: [${name}]  ids: [${ids}]`);
Rastalamm
  • 1,712
  • 3
  • 23
  • 32
Azeem Aslam
  • 554
  • 5
  • 19
  • Thanks a lot, it is really helpful, but when output the value, I lost the double quota `[jack,tom]`, which I want to get `["jack", "tom"]` – Bill Mar 26 '19 at 03:13