-2

I'm trying to get an array of objects into an object-format with the values as the keys of the new object.

Let's say I got this data:

const data = [
{
  key: "foo",
  value: "xyz",
  classLabel: "Test"
},
{
  key: "foo",
  value: "abc",
  classLabel: "Test"
},
{
  key: "bar",
  value: "aaa",
  classLabel: "Test"
}]

And the format I want to build is like this:

const expected = {
  foo: ["xyz", "abc"],
  bar: ["aaa"]
}

The values are transferred to the keys and pushed into the same array for duplicate keys. So far I only extracted the keys with:

const result = [...new Set(data.map(item => item.key))];  // ["foo", "bar"]
isherwood
  • 58,414
  • 16
  • 114
  • 157
Louie
  • 17
  • 3

2 Answers2

4

const data = [
{
  key: "foo",
  value: "xyz",
  classLabel: "Test"
},
{
  key: "foo",
  value: "abc",
  classLabel: "Test"
},
{
  key: "bar",
  value: "aaa",
  classLabel: "Test"
}];

let expected = data.reduce((out, {key, value}) => {
  out[key] = out[key] || [];
  out[key].push(value);
  return out;
}, {});

console.log(expected);
junvar
  • 11,151
  • 2
  • 30
  • 46
0

The following should work:

const data = [
  {
    key: "foo",
    value: "xyz",
    classLabel: "Test",
  },
  {
    key: "foo",
    value: "abc",
    classLabel: "Test",
  },
  {
    key: "bar",
    value: "aaa",
    classLabel: "Test",
  },
];

const mapToObj = (arr) => {
  let obj = {};
  for (let i in arr) {
    let objKey = arr[i].key;
    obj[objKey]
      ? Object.assign(obj, { [arr[i].key]: [obj[objKey], arr[i].value] })
      : Object.assign(obj, { [arr[i].key]: arr[i].value });
  }
  return obj;
};

console.log(mapToObj(data));
Dharman
  • 30,962
  • 25
  • 85
  • 135
DaanKode
  • 131
  • 5