将对象的特定属性与JavaScript合并 [英] Merge specific properties of objects together with JavaScript

查看:79
本文介绍了将对象的特定属性与JavaScript合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个像这样的对象数组:

So I have an array of objects like so:

[
  {
    name: "Joe Smith",
    job: "Janitor",
    age: 35,
    id: "3421"
  },
  {
    name: "George Henderson",
    job: "CEO",
    age: 43,
    id: "5098"
  },
  {
    name: "Joe Smith",
    job: "Cook",
    age: 35,
    id: "3421"
  },
  {
    name: "Sam Doe",
    job: "Technician",
    age: 22,
    id: "1538"
  },
  {
    name: "Joe Smith",
    job: "Dishwasher",
    age: 35,
    id: "3421"
  } 
]

您可以看到,乔·史密斯(Joe Smith)有三份工作.我想做的就是将他的所有工作组合成一个对象,就像这样:

As you can see, Joe Smith has three jobs. What I want to do is to combine all of his jobs into one object like so:

{
   name: "Joe Smith",
   job: "Janitor, Cook, Dishwasher",
   age: 35,
   id: "3421"
}

我希望能够与拥有多个工作的任何人一起执行此操作.另外,可能有多个同名的人,因此最好通过其ID而非姓名来识别这些人.

I'd like to be able to do this with any person who has multiple jobs. Also, there could be multiple people with the same name, so it would be better to identify the people by their id, not name.

我将如何去做?如果使用Lodash之类的库可以简化代码,那是很好的选择,但是我想不出一种比遍历数组更简单的方法,但这会变得很复杂.

How would I go about doing this? Using a library like Lodash is great if it simplifies the code, but I can't think of a simpler way than iterating through the array, but that can get complex.

谢谢!

推荐答案

使用lodash,您可以对数组进行分组并映射所需的属性.

With lodash, you could group the array and map the wanted properties.

var data = [{ name: "Joe Smith", job: "Janitor", age: 35, id: "3421" }, { name: "George Henderson", job: "CEO", age: 43, id: "5098" }, { name: "Joe Smith", job: "Cook", age: 35, id: "3421" }, { name: "Sam Doe", job: "Technician", age: 22, id: "1538" }, { name: "Joe Smith", job: "Dishwasher", age: 35, id: "3421" }],
    result = _(data)
        .groupBy('id')
        .map(array => ({ ...array[0], job: _.join(_.map(array, 'job'), ", ") }))
        .value();

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

这篇关于将对象的特定属性与JavaScript合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆