从对象数组中提取值

时间:2019-04-15 18:57:28

标签: javascript

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

[
    {
        "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" } ] }, ] 

2 个答案:

答案 0 :(得分:0)

您可以通过使用 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)

答案 1 :(得分:0)

您可以reduce $string = preg_replace('/O/', 'E', $string, 1); 数组并根据users对其进行分组。解构每个用户并分别获取属性的namename。遍历rest的键,并检查该键是否已存在于嵌套值中。如果存在,则创建一个值数组。否则,只需添加值:

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

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