简体   繁体   English

从对象数组中提取值

[英]Extracting values from array of objects

I have an array that looks like this one: 我有一个看起来像这样的数组:

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

]

I want to merge the objects whose name match. 我想合并名称匹配的对象。 I found this helper function: 我找到了这个辅助函数:

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

But it is not budging. 但它没有动摇。 Any ideas on how I could go about this? 关于如何解决这个问题的任何想法? The expected outcome should be: 预期结果应该是:

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

You can achive this by using Map object for optimization and then converting it back to array. 您可以通过使用Map对象进行优化然后将其转换回数组来实现此目的。 Check out code below. 查看下面的代码。

 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) 

You could reduce the users array and group them based on the name . 您可以reduce users数组并根据name对它们进行分组。 Destructure each user and get the name and rest of the properties separately. 对每个用户进行构造并分别获​​取属性的namerest Loop through the keys of rest and check if the key already exists in the nested value. 循环遍历rest键并检查密钥是否已存在于嵌套值中。 If it exists, create an array of values. 如果存在,则创建一个值数组。 Else, just add the value: 否则,只需添加值:

 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 }]) 

This is what the merged object looks like: 这是merged对象的样子:

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

Use Object.values() to get the values of this object to an array 使用Object.values()将此对象的值获取到数组

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

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