【问题标题】:combine javascript objects with inner array with same key (similar to foriegn key )将 javascript 对象与具有相同键的内部数组组合起来(类似于外键)
【发布时间】:2017-10-24 07:38:08
【问题描述】:
           Obj1 = [
                {
                    'id':1,
                    'name':'apple'
                },
                {
                    'id':2,
                    'name':'mango'
                }
            ]

            Obj2 = [
                {
                    'parentId' : 1,
                    'time': [1,2,3]
                },
                {
                    'parentId' : 1,
                    'time': [4,5,6]
                },
                {
                    'parentId' : 1,
                    'time': [7,8,9]
                },
                {
                    'parentId' : 2,
                    'time': [11,12]
                }
            ]


            result = [
            {
                    'id':1,
                    'name':'apple',
                    'time': [1,2,3,4,5,6,7,8,9]
                },
                {
                    'id':2,
                    'name':'mango',
                    'time': [11,12]
                },
            ]

如何组合这两个具有相同键的对象 NodeJs 或 Javascript 并获取以下结果对象。

不使用 Jquery 或任何其他框架。

注意:NodeJs 应用程序

【问题讨论】:

  • 你试过什么?你知道如何使用哈希表吗?

标签: javascript arrays node.js merge


【解决方案1】:

您可以使用Array#map()Array#filter()concat()

解释

arr1.map(a1=>{...}) => 基于arr1创建一个新数组

arr2.filter(a2=>a2.prentId===a1.id) => 保留所有parentId 等于当前id 的项目

.map(a2=>a2.time) => 只保留time 数组

let times 是一个时间数组:[[1,2,3],[4,5,6]]

[].concat.apply([], times) => 展平times 嵌套数组

const arr1=[{id:1,name:"apple"},{id:2,name:"mango"}],arr2=[{parentId:1,time:[1,2,3]},{parentId:1,time:[4,5,6]},{parentId:1,time:[7,8,9]},{parentId:2,time:[11,12]}];

let result = arr1.map(a1=>{
  let times = arr2.filter(a2=>a2.parentId===a1.id).map(a2=>a2.time);
  a1.time = [].concat.apply([], times);
  return a1;
});

console.log(result);

【讨论】:

  • 在你写作时,什么你使用,你没有解释为什么你使用所有的东西。
【解决方案2】:

const obj1=[{'id':1,'name':'apple'},{'id':2,'name':'mango'}];
const obj2=[{'parentId':1,'time':[1,2,3]},{'parentId':1,'time':[4,5,6]},{'parentId':1,'time':[7,8,9]},{'parentId':2,'time':[11,12]}];

const res = obj1.map(el => Object.assign(el, {time: obj2.filter(i => el.id === i.parentId).map(({time}) => time).join(',').split(',')}))

console.log(res)

【讨论】:

    猜你喜欢
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多