简体   繁体   English

如何有效地匹配两个不同的javascript对象上的id并将它们合并在一起?

[英]How to efficiently match ids on two different javascript objects and merge them together?

This is somewhat similar to a join table. 这有点类似于联接表。 I have two different javascript objects. 我有两个不同的javascript对象。 One of these objects is an array of objects, where one of the properties in that object is an array of ids. 这些对象之一是对象数组,其中该对象中的属性之一是ID数组。 These ids map directly to another array of javascript objects. 这些ID直接映射到另一个javascript对象数组。

ex. 恩。

users = [{
  name: 'Bob',
  birthday: '01-02-1990',
  favorite_color_ids: ['2', '4', '6']
},
{
....etc

}]

colors: [{
  id: 2,
  name: 'red',
  hex_val: '#FF0000'
},
{
  ...etc
}]

I want to create another property on each object in the users array, called 'favorite_color_names'. 我想在用户数组中的每个对象上创建另一个属性,称为“ favorite_color_names”。 What would be the most efficient way to do this? 什么是最有效的方法? Currently have many nested _.each operations. 当前有许多嵌套的_.each操作。

Expanding on my comment above, if you need to access the colors by ID frequently, but can't change the structure from an Array, I'd just go ahead and dynamically create an object structure that references each color by ID. 在上面的评论中扩展一下,如果您需要经常按ID访问颜色,但是不能从Array更改结构,那么我将继续并动态创建一个对象结构,以按ID引用每种颜色。

var colors_by_id = {}

colors.forEach(color) {
    colors_by_id[color.id] = color
})

Then you can make your arrays of names if you wish for each user (though it would seem less important since you can now easily get it on the fly) . 然后,您可以根据需要为每个用户创建名称数组(尽管它似乎不那么重要,因为您现在可以随时随地轻松获取它)

users.forEach(user) {
    user.favorite_color_names = user.favorite_color_ids.map(function(id) {
        return colors_by_id[id].name
    })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM