Miguel.G
Miguel.G

Reputation: 387

Get data from an array of dictionaries in Javascript

I'm working with a web framework and I'm using variables from Python into Javascript code.

I get next array in Python, which can contain more than one cell with dictionaries inside it:

 [[{'lacp_use-same-system-mac': u'no'}, {'lacp_mode': u'passive'}, {'lacp_transmission-rate': u'slow'}, {'lacp_enable': u'no'}]]

I want to be able to access every cell array and, after that, get every keys from the dictionary inside this cell array. Up to now, I only have arrays or dictionaries, so for both cases I did next:

var X = JSON.parse(("{{X|decodeUnicodeObject|safe}}").replace(/L,/g, ",").replace(/L}/g, "}").replace(/'/g, "\""));

Where X is the Python variable. Unfortunately, this does not run with the array I wrote above.

How can I do that?

Thanks beforehand,

Regards.

Upvotes: 1

Views: 4965

Answers (1)

Ced
Ced

Reputation: 17337

I want to be able to access every cell array and, after that, get every keys from the dictionary inside this cell array

If I understood correctly you want to get the keys of a nested array.

Note: your array isn't valid js.

const arrarr = [[{key1: 'val1'}, {key2: 'val2'}], [{key3: 'val3'}, {key4: 'val4'}]];
    
arrarr.forEach(arr => {
  arr.forEach(e => {
    Object.keys(e).forEach(k => console.log(k))
  })
})

If the depth of nests is of arbitrary depth you can use recursion and check if the child is an array, if it is keep going, else get the keys.

Upvotes: 1

Related Questions