0

I have the following JSON (snippet):

"1": {
  "Name": [
    "Person1",
    "Person2",
    "Person3",
    "Person4",
    "Person5"
  ]
}
"4"{
  "Name": [
    "AnotherPerson1",
    "AnotherPerson2",
    "AnotherPerson3",
    "AnotherPerson4",
    "AnotherPerson5"
  ]
}
...

I don't know the key value (it doesn't increase linearly) and I don't know the different values inside "Name" (only that they are inside "Name", are strings, and total 5).

I want to return all first strings under "Name" and their respective root(?) key. So "Person1" & "1"; "AnotherPerson1" & "4", etc.

I've only managed to make it work when I know the key value but it's too long to write.

console.log(data[1]["Name"][1]);

2 Answers 2

1
var keys = Object.keys(data);

keys.forEach(function(key) {
  console.log(data[key].Name[0], 'on root key', key);
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can iterate over Object.entries() array to map the data to a more useful structure.

I'm not 100% clear what the structure you are looking for is but I think what you want is something like:

const data={1:{Name:["Person1","Person2","Person3","Person4","Person5"]},4:{Name:["AnotherPerson1","AnotherPerson2","AnotherPerson3","AnotherPerson4","AnotherPerson5"]}};

const res = Object.entries(data).reduce((a,[key,{Name}])=> {
   Name.forEach(name => a.push({name, key}));
   return a;
},[]);

console.log(res)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.