Home > Enterprise >  How do I add lists from objects to other objects (connected with id)
How do I add lists from objects to other objects (connected with id)

Time:10-04

I have two JSON files and I need to get the program to log the names from the other and under each name I need log a list of titles that belong to that name from another JSON file. They are connected with an id but on the other file the correct id is named "id" and on the other it's "userId" (and there is a key id also but refers to something else.

The data is from here: https://jsonplaceholder.typicode.com/posts and here https://jsonplaceholder.typicode.com/users

What I need is something like this:

name1
-title1
-title2
-title3
-title4

name2
-title5
-title6
-title7
-title8

...

CodePudding user response:

One solution is to use a nested for-loop:

for (let user of users) {
  console.log(user.name);
  for (let title of titles) {
    if (user.id == title.userId) {
      console.log(`\t- ${title.title}`);
    }
  }
}

Results in something like:

Leanne Graham
    - sunt aut facere repellat provident occaecati excepturi optio reprehenderit
    - qui est esse
    - ea molestias quasi exercitationem repellat qui ipsa sit aut
    - eum et est occaecati
    - nesciunt quas odio
    # ...
Ervin Howell
    - et ea vero quia laudantium autem
    - in quibusdam tempore odit est dolorem
    # ...

  • Related