1

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.

Both id 1 and id 2 are dynamic and can grow. Id 1 will always be last name and id 2 will always be first name.

10
  • What actually associates "John" with the last name of "Smith"? Is it because "Smith" is the first Last Name listed and "John" is the first First name listed that they are "linked" Commented Jun 7, 2022 at 2:50
  • why not John Blogs !? Commented Jun 7, 2022 at 2:55
  • "Id 1 will always be last name and id 2 will always be first name." If you're not using the IDs to link related properties, how do you know which first name belongs to which last name? Commented Jun 7, 2022 at 2:59
  • @NickParsons Position of the object in the array. So index 0 linked to index 2, index 1 linked to index 3, etc. Commented Jun 7, 2022 at 3:01
  • 1
    That's a pretty nasty approach. Then you first have to count the number of distinct IDs to figure out which values belong together. Commented Jun 7, 2022 at 3:04

2 Answers 2

3
  • .reduce() groups each ['value'] under ['label']['First Name'] or ['label']['Last Name'] which become arrays of group object.

  • 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()

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));

Sign up to request clarification or add additional context in comments.

Comments

0

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.

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. 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'],
    }
})

1 Comment

Unfortunately, the first name and last names from the objects aren't related by ids and instead are related by position. Although this approach would work if OP changes their data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.