简体   繁体   English

Javascript修改对象数组和concat值

[英]Javascript modify array of objects and concat value

I have an array of objects like this:我有一个这样的对象数组:

const data = [
  { id: '1', label: 'Last Name', value: 'Smith' },
  { id: '1', label: 'Last Name', value: 'Blogs' },
  { id: '2', label: 'First Name', value: 'John' },
  { id: '2', label: 'First Name', value: 'Joe' }
];

I'm trying to get an output like this:我试图得到这样的输出:

const output = [
  {key: 'Employee', value: 'John Smith'},
  {key: 'Employee', value: 'Joe Blogs'}
];

I was looking at using reduce, but am stuck on how to properly get a condition to say that if id is 2, then add to output.value, and if id is 1 then concat output.value to the value already there.我正在考虑使用reduce,但我一直坚持如何正确获得一个条件,即如果id为2,则添加到output.value,如果id为1,则将output.value连接到已经存在的值。

Both id 1 and id 2 are dynamic and can grow. id 1 和 id 2 都是动态的并且可以增长。 Id 1 will always be last name and id 2 will always be first name. ID 1 永远是姓氏,id 2 永远是名字。

  • .reduce() groups each ['value'] under ['label']['First Name'] or ['label']['Last Name'] which become arrays of group object. .reduce() ['label']['First Name']['label']['Last Name'] ['value']分组,它们成为group对象的数组。

  • Next .map() iterates through output['First Name'] and then current values of output['First Name'] and output['Last Name'] are concatenated and added to a new object created by Object.assign()接下来.map()遍历output['First Name'] ,然后将output['First Name']output['Last Name']的当前值连接起来并添加到由Object.assign()创建的新对象中

 const data = [ { id: '1', label: 'Last Name', value: 'Smith' }, { id: '1', label: 'Last Name', value: 'Blogs' }, { id: '2', label: 'First Name', value: 'John' }, { id: '2', label: 'First Name', value: 'Joe' } ]; function fullName(objArray) { let output = objArray.reduce((group, current) => { if (!group[current['label']]) { group[current['label']] = []; } group[current['label']].push(current.value); return group }, {}); console.log(`.reduce() returns: (scroll down for final result)`); console.log(output); console.log(`fullName(data) returns:`); return output['First Name'].map((first, index) => Object.assign({}, { key: 'Employee', value: first + ' ' + output['Last Name'][index] }) ); } console.log(fullName(data));

You need to first group the related items.您需要首先对相关项目进行分组。 These days you can use the Map object but normally most people would simply use an empty object ( {} ) partly because that's how it's always been done so other programmers can easily read your code and partly because the syntax is nicer to use.现在您可以使用Map对象,但通常大多数人会简单地使用一个空对象 ( {} ),部分原因是它一直都是这样做的,因此其他程序员可以轻松阅读您的代码,部分原因是语法更好用。

So the basic idea would be this:所以基本的想法是这样的:

let group = {};

arrayData.forEach(item => {
    let id = item.id;

    if (!group[id]) {
        // if item does not exist in the group yet
        // then create item
        group[id] = {}
    }

    group[id][item.some_key] = item.some_value;
})

Then after grouping you can loop through the group and construct a new array:然后在分组之后,您可以遍历组并构造一个新数组:

let result = [];

for (let i in group) {
    result.push({
        some_key_you_want: i.xxx + i.yyy
    })
}

Now you have a result array containing the data you want.现在您有了一个包含所需数据的result数组。 Of course we can write this in many different ways but the above is the general outline of the idea.当然,我们可以用许多不同的方式来写这个,但以上是这个想法的大致轮廓。

In your case we can do:在您的情况下,我们可以这样做:

let group = {}

data.forEach(item => {
    let id = item.id;
    if (!group[id]) group[id] = {};
    group[id][item.label] = item.value;
})

const result = Object.values(group).map(item => {
    return {
        key: 'Employee',
        value: item['First Name'] + ' ' + item['Last Name'],
    }
})

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

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