对象JS的动态键名

时间:2018-11-28 16:21:58

标签: javascript arrays object lodash

嗨,我有一个数组和一个数组对象。

我想将此数组与对象中的每个数组合并,并删除重复项并将其推入另一个对象。新对象中的键应该是我们要合并到的数组名称。

我尝试了不同的方法,没有解决问题。

请咨询。

const data = [{
    name: 'BMW',
    value: '25641'
  }, {
    name: 'Apple',
    value: '45876'
  },
  {
    name: 'Benz',
    value: '65784'
  },
  {
    name: 'Toyota',
    value: '254'
  }
]

const obj = {
  carsList: [{
    name: 'Ford',
    value: '47563'
  }, {
    name: 'Toyota',
    value: '254'
  }],
  pastriesList: [],
  fruitsList: [{
    name: 'Apple',
    value: '45876'
  }, {
    name: 'Pineapple',
    value: '84523'
  }]
}

const result = {};

_.forEach(obj, (value, key) => {
  this[key] = _.uniqWith(_.concat(data, value), _.isEqual);
  result[key] = this[key];
})

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

预期输出:

{
carsList: [
  {
    "name": "BMW",
    "value": "25641"
  },
  {
    "name": "Apple",
    "value": "45876"
  },
  {
    "name": "Benz",
    "value": "65784"
  },
  {
    "name": "Toyota",
    "value": "254"
  },
  {
    "name": "Ford",
    "value": "47563"
  }
],
pastriesList:
[
  {
    "name": "BMW",
    "value": "25641"
  },
  {
    "name": "Apple",
    "value": "45876"
  },
  {
    "name": "Benz",
    "value": "65784"
  },
  {
    "name": "Toyota",
    "value": "254"
  }
],
fruitsList: 
[
  {
    "name": "BMW",
    "value": "25641"
  },
  {
    "name": "Apple",
    "value": "45876"
  },
  {
    "name": "Benz",
    "value": "65784"
  },
  {
    "name": "Toyota",
    "value": "254"
  },
  {
    "name": "Pineapple",
    "value": "84523"
  }
]

非常感谢您的帮助。

0 个答案:

没有答案