繁体   English   中英

从对象数组中提取值

[英]Extracting values from array of objects

我有一个看起来像这样的数组:

[
    {
        "users": [
            {
               "name": "John",
               "location": "USA",
                "age": "34",
            },
           {
                "name": "John",
               "location": "California",
                "address": "Silk Road 123"
            },
           {
               "name": "Jane",
               "last-name": "Edmus"
               "location": "USA"
            }
        ]
    },

]

我想合并名称匹配的对象。 我找到了这个辅助函数:

 findByMatchingProperties = (set, properties) => {
  return set.filter(function (entry) {
      return Object.keys(properties).every(function (key) {
          return console.log(entry[key] === properties[key]);
      });
  });
}

但它没有动摇。 关于如何解决这个问题的任何想法? 预期结果应该是:

 [ { "users": [ { "name": "John", "location": ["USA", "California"}, "age": "34", "address": "Silk Road 123" }, { "name": "Jane", "last-name": "Edmus" "location": "USA" } ] }, ] 

您可以通过使用Map对象进行优化然后将其转换回数组来实现此目的。 查看下面的代码。

 const users = [ { "name": "John", "location": "USA", "age": "34" }, { "name": "John", "location": "California", "address": "Silk Road 123" }, { "name": "John", "location": "Foo", "bar": "baz" }, { "name": "Jane", "last-name": "Edmus", "location": "USA" } ]; const mergeObjectsExceptProps = (exceptProps, o1, o2) => Object.entries(o2).reduce((acc, [ k, v ]) => { if (exceptProps.includes(k)) { return acc } let propValueToSet if (acc.hasOwnProperty(k)) { propValueToSet = [ ...(Array.isArray(acc[k]) ? acc[k] : [ acc[k] ]), v ] } else { propValueToSet = v } return { ...acc, [k]: propValueToSet, } }, o1) const usersMap = new Map() for (const user of users) { const foundUser = usersMap.get(user.name) if (foundUser) { usersMap.set(user.name, mergeObjectsExceptProps([ 'name' ], foundUser, user)) } else { usersMap.set(user.name, user) } } const result = [ ...usersMap.values() ] console.log(result) 

您可以reduce users数组并根据name对它们进行分组。 对每个用户进行构造并分别获​​取属性的namerest 循环遍历rest键并检查密钥是否已存在于嵌套值中。 如果存在,则创建一个值数组。 否则,只需添加值:

 const input = [{users:[{name:"John",location:"USA",age:"34"},{name:"John",location:"California",address:"Silk Road 123"},{name:"Jane","last-name":"Edmus",location:"USA"}]}]; const merged = input[0].users.reduce((acc, o) => { const { name, ...rest } = o; const group = acc[name]; // check if name already exists in the accumulator if(group) { Object.keys(rest).forEach(key => { if(key in group) group[key] = [].concat(group[key], o[key]) else group[key] = o[key]; }) } else acc[name] = o; return acc; },{}) const users = Object.values(merged) console.log([{ users }]) 

这是merged对象的样子:

{
  "John": {
    "name": "John",
    "location": ["USA", "California"],
    "age": "34",
    "address": "Silk Road 123"
  },
  "Jane": {
    ...
  }
}

使用Object.values()将此对象的值获取到数组

暂无
暂无

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

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