-1

How to convert the following object into the following output in JavaScript?

[
    {
        "attrTitle": "color",
        "attrValue": "Green"
    },
    {
        "attrTitle": "size",
        "attrValue": "M"
    },
    {
        "attrTitle": "size",
        "attrValue": "L"
    },
    {
        "attrTitle": "size",
        "attrValue": "S"
    },
    {
        "attrTitle": "color",
        "attrValue": "Red"
    }
]

Output I expected is the following

[
    {
        "attrTitle": "color",
        "attrValue": ["Red", "Green"]
    },
    {
        "attrTitle": "size",
        "attrValue": ["S","L","M"]
    }
]

When I try with this code it does not work.

const variantAttr = productAttr.reduce((i, attr) => {
  const { attrTitle, attrValue } = attr
  i[attrTitle] = i[attrTitle] ?? []
  i[attrTitle].push(attrValue)
  return i
}, {})
Hari Dahal
  • 113
  • 1
  • 3
  • 11
  • Your attempt is pretty close, and it's around 90% of the way there (that's why you should always share your attempt when posting your question initially). All you have to do now is grab the entries of the object in `variantAttr` and map them to objects of your desired form: `const res = Object.entries(variantAttr).map(([attrTitle, attrValue]) => ({attrTitle, attrValue}))`. I share a similar approach [here](https://stackoverflow.com/a/60444325/5648954), but use a `Map` instead of an object to group, and then `Array.from()` to convert the Map into an array of objects. – Nick Parsons Jan 08 '23 at 09:40

1 Answers1

1
const input = [ ... ];

const output = input.reduce((acc, curr) => {
    const existingAttr = acc.find(attr => attr.attrTitle === curr.attrTitle);
    if (existingAttr) {
        existingAttr.attrValue.push(curr.attrValue);
    } else {
        acc.push({
            attrTitle: curr.attrTitle,
            attrValue: [curr.attrValue]
        });
    }
    return acc;
}, []);
  • 1
    Code-only answers aren't generally considered high quality; please explain what your code does too. (Also, with a suitably large number of attributes, this will be slow due to the repeated use of `.find`.) – AKX Jan 08 '23 at 09:08
  • It's work very perfectly ... @Tigran Vardanyan The solution is exactly what I'm looking for Thank you very much – Hari Dahal Jan 08 '23 at 09:15