1

I have the following object:

  a = [
{id: 1, comp: 'ans', stat: 'www', value: ['1', '2']},
{id: 2, comp: 'qsn', stat: 'xxx', value: ['a', 'b']},
{id: 3, comp: 'ans', stat: 'yyy', value: ['3', '4']},
{id: 4, comp: 'qsn', stat: 'zzz' ,value: ['c', 'd']}
]

I wanted the best possible way to combine the value array inside of the objects where the key comp matches and the other properties that do not match have the property of the first element intact and concat only the values array. The output I want to achieve in the above scenario is :

[
{id: 1, comp: 'ans', stat: 'www', value: ['1', '2', '3', '4']},
{id: 2, comp: 'qsn', stat: 'xxx', value: ['a', 'b', 'c', 'd']}
]
2
  • 1
    What did you try so far? Commented Aug 25, 2020 at 11:01
  • Search for "Group array of objects by property javascript", that will help you create two arrays. To merge, do something like group.reduce((o1, o2) => ({ ...o1, value: o1.value.concat(o2.value) })) Commented Aug 25, 2020 at 11:03

2 Answers 2

2

You can group the objects by comp using the function Array.prototype.reduce and the function Object.values to extract the grouped objects.

const a = [{id: 1, comp: 'ans', stat: 'www', value: ['1', '2']},{id: 2, comp: 'qsn', stat: 'xxx', value: ['a', 'b']},{id: 3, comp: 'ans', stat: 'yyy', value: ['3', '4']},{id: 4, comp: 'qsn', stat: 'zzz' ,value: ['c', 'd']}],
      result = Object.values(a.reduce((a, {comp, value, ...rest}) => {
        (a[comp] || (a[comp] = {...rest, comp, value: []})).value.push(...value);
        return a;
      }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

1 Comment

@vivek-jain the css is to expand the console, don't remove it.
2

I think a more readable approach is necessary

const a = [{
        id: 1,
        comp: 'ans',
        stat: 'www',
        value: ['1', '2']
    },
    {
        id: 2,
        comp: 'qsn',
        stat: 'xxx',
        value: ['a', 'b']
    },
    {
        id: 3,
        comp: 'ans',
        stat: 'yyy',
        value: ['3', '4']
    },
    {
        id: 4,
        comp: 'qsn',
        stat: 'zzz',
        value: ['c', 'd']
    }
]

const result = [];

for (let aChild of a) {
    const sameComp = result.find(res => res.comp === aChild.comp);
    if (sameComp) {
        sameComp.value = sameComp.value.concat(aChild.value);
    } else {
        result.push(aChild);
    }
}

console.log(result);

Comments

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.