C
C
codercat2015-10-24 07:55:06
JavaScript
codercat, 2015-10-24 07:55:06

How do you usually combine 2 entities into one?

I don’t know how you can ask a question correctly, so I’ll try to explain with an example.
The API of some services returns, for example, entries and users in 2 different arrays:

{
  posts: [
    {
      user_id: 1,
      title: 'Заголовок записи #1'
      text: 'Текст записи #1'
    },
    ...
  ],
  users: [
    {
      id: 1,
      fullname: 'Пол Аллен'
    },
    ...
  ]
}

As a rule, for the convenience of displaying a list of posts with an indication of the author for each post, I solve such problems in a similar way:
var usersWithIdIndex = [];
for(var i in response.users) {
usersWithIdIndex[response.users[i].id] = response.users[i];
}

for(var i in response.posts) {
response.posts[i]['user'] = users[response.posts[i].user_id];
}

Is my decision correct and what are such decisions generally called? Are there any typical patterns for implementing such tasks?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dtestyk, 2015-10-24
@codercat

there are solutions using third-party libraries
, more options with examples on fiddle,
but in general yours is quite good (except for modifying someone else's response object)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question