Home > Mobile >  How to get unique values from js object with array in value
How to get unique values from js object with array in value

Time:07-20

I need some help figuring out how to get unique values from an array of objects in this format. I have reviewed several examples but none had the values of a key being an array. Thanks in advance for your advice.

I have a JS array with complex objects with some object values being arrays:

let array = [
    { key1: ["one","two","four"], Key2: [1,2,4] },
    { key1: ["two","four","six"], Key2: [2,4,6] },
    { key1: "nine", Key2: 9 },
];

I want to get the unique values for all keys in the object (so it will support any structure) and output like this:

[
{Key1: ["one","two","four", "six", "nine"]},
{Key2: [1,2,4,6,9]}
]

CodePudding user response:

You can try this :

let data = [
    { key1: ["one","two","four"], Key2: [1,2,4] },
    { key1: ["two","four","six"], Key2: [2,4,6] },
    { key1: "nine" },
];

let keys = [...new Set(data.flatMap(d => Object.keys(d)))];

let values = Object.fromEntries(
    keys.map(k => [
        k,
        [... new Set(data.flatMap(d => d[k] ? d[k] : null).filter(v => v != null && v != undefined))] 
    ])
);
console.log(values);

CodePudding user response:

You could try something like this:

let array = [
  { key1: ["one", "two", "four"], Key2: [1, 2, 4] },
  { key1: ["two", "four", "six"], Key2: [2, 4, 6] },
  { key1: "nine", Key2: 9 },
];

let obj = {};
array.forEach((item) =>
  Object.entries(item).forEach((entry) => {
    if (!obj[entry[0]]) obj[entry[0]] = [];
    !Array.isArray(entry[1])
      ? obj[entry[0]].push(entry[1])
      : (obj[entry[0]] = [...obj[entry[0]], ...entry[1]]);
  })
);

let result = [];
Object.entries(obj).forEach((entry) =>
  result.push({
    [entry[0]]: Array.from(new Set(entry[1])),
  })
);

console.log(obj);
console.log("res", result);
  • Related