Home > Software engineering >  Read the list of Ids from nested JSON
Read the list of Ids from nested JSON

Time:04-01

I need to read the ids from nested loop using Javascript.

Input:

let data = [3,[{
"Id": 30,
"Name":"John"
},{
"Id": 33,
"Name":"Jill"
},{
"Id": 34,
"Name":"Jerena"
}]]

Output:

[30,33,34]

I'm stuck with this from sometime. Using maps let Ids = [data[0][1]].map(a => a.Id);

CodePudding user response:

Try this

let data = [3,[{
"Id": 30,
"Name":"John"
},{
"Id": 33,
"Name":"Jill"
},{
"Id": 34,
"Name":"Jerena"
}]]

console.log(data[1].map(r => r.Id))

CodePudding user response:

yours example:

let Ids = [data[0][1]].map(a => a.Id);

so, you have an array with 2 items

the first element with index = 0 will be number 3

the second element with index = 1 will be an array.

so:

console.log(data[0]) // 3
console.log(data[1]) // [...]

or we can use destructuring

const [firstNumber, array] = data;
//then
cosnt ids = array.map(i => i.Id)

UPDATE: if you are using typescript and getting this error:

getting this error map' does not exist on type 'number | { Id: number; name: string}[]'. Property 'map' does not exist on type 'number'.

You need to defined type of variable correcly.

we can use tuple types

var employee: [number, { Id: number; name: string}[]] = [1, [...]];
  • Related