将一个Javascript对象的键和值插入另一个Javascript对象

时间:2017-12-21 16:21:47

标签: javascript

我们说我有以下两个Javascript对象:

let platformModules = [
  {
    id: 1,
    name: 'Module One',
    icon: 'icon-01',
    deleted: false
  },
  {
    id: 3,
    name: 'Module Two',
    icon: 'icon-02',
    deleted: false
  }
]

let companyModules = [
  {
    id: 1,
    companyId: 4,
    name: 'Our second module',
    enabled: true,
    position: 2
  },
  {
    id: 3,
    companyId: 4,
    name: 'Our first module',
    enabled: true,
    position: 1
  }
]

我希望能够取得icon密钥(以及它的价值)  来自platformModules并将其插入基于companyModules的新对象中,如下例所示:

let displayModules = [
  {
    id: 1,
    companyId: 4,
    name: 'Our second module',
    enabled: true,
    position: 2,
    icon: 'icon-01'
  },
  {
    id: 3,
    companyId: 4,
    name: 'Our first module',
    enabled: true,
    position: 1,
    icon: 'icon-01'
  }
]

我尝试了以下操作,但它无效:

function findAndMerge (source, target, findKey) {
  for (var key in source) {
    if (source.hasOwnProperty(key) && source[key] === findKey) {
      target[key] = source[key]
    }
  }
}
let displayModules = findAndMerge(platformModules, companyModules, icon)

任何帮助,指针将不胜感激。非常感谢。

1 个答案:

答案 0 :(得分:0)

使用数组的map()循环遍历基础数组(companyModules),然后使用platformModulesObject.assign()分配对象。请尝试以下方法:

let platformModules = [
  {
    id: 1,
    name: 'Module One',
    icon: 'icon-01',
    deleted: false
  },
  {
    id: 3,
    name: 'Module Two',
    icon: 'icon-02',
    deleted: false
  }
]

let companyModules = [
  {
    id: 1,
    companyId: 4,
    name: 'Our second module',
    enabled: true,
    position: 2
  },
  {
    id: 3,
    companyId: 4,
    name: 'Our first module',
    enabled: true,
    position: 1
  }
]

var displayModules = companyModules.map(function(item, i){
  return Object.assign({'icon':platformModules[i].icon},item);
});
console.log(displayModules);