1

What I have:

myArray = [ {type: "My Application"}, {type: "My Component"}, {color: ["red"] } ]

What I need:

withUniqueKeys = [ {type: ["My Application", "My Component"] }, {color: ["red"]} ]

How would I loop through myArray to get an array like withUniquKeys? I've been toying with this WAAAYYYY too long. A lodash solution would be okay too.

1
  • 1
    do you have only type and color or different and/or more properties? Commented Apr 5, 2019 at 18:24

5 Answers 5

4

You can use reduce and Object.entries

let myArray = [ {type: "My Application"}, {type: "My Component"}, {color: "red" } ]

let op = myArray.reduce((op,inp)=>{
  let [key,value] = Object.entries(inp)[0]
  op[key] = op[key] || []
  op[key].push(value)
  return op
},{})

// in case you want property with one value to be object only

let final = Object.entries(op)
           .map(([key,value]) => ( {[key]: value.length === 1 ? value[0] : value}))

console.log(final)

IMO it's better to keep you structure of data consistent something like this,so it becomes easy to use for later purposes else you need to check whether the value is just a string or array and than apply methods

let myArray = [ {type: "My Application"}, {type: "My Component"}, {color: "red" } ]

let op = myArray.reduce((op,inp)=>{
  let [key,value] = Object.entries(inp)[0]
  op[key] = op[key] || []
  op[key].push(value)
  return op
},{})

console.log(op)

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

2 Comments

Apparently OP doesn't want arrays if there is only one value (e.g. color).
@Jeto updated for that case too, but IMO it's better to have a consistent strcture
1

You can do it with Array.prototype.reduce() and Object.entries() like this:

const arr = [{type: "My Application"}, {type: "My Component"}, {color: "red" }];

const result = Object.entries(arr.reduce((acc, x) => {
  Object.entries(x).forEach(([k, v]) => {
    acc[k] = [...(acc[k] || []), v];
  });
  return acc;
}, {})).map(([k, v]) => ({ [k]: v.length > 1 ? v : v[0] }));

console.log(result);

Comments

1

Try this:

  1. Reduce initial array to group entries by keys
  2. Map object entries to array of corresponding objects

let myArray = [ {type: "My Application"}, {type: "My Component"}, {color: ["red"] } ]

myArray = myArray.reduce((acc, el) => {
  let prop = Object.keys(el)[0];
  if (!acc[prop]) acc[prop] = [el[prop]];
  else acc[prop].push(el[prop])
  return acc;
},{})

myArray = Object.keys(myArray).map(d => ({[d]:myArray[d].length ===1?myArray[d][0]:myArray[d]}));

console.log(myArray)

Comments

0

First, you can use Array.reduce() to do the grouping by the keys. Then, on a second step, you can use Array.map() over the generated Object.entries() to get the desired structure:

let myArray = [
  {type: "My Application", category: "game"},
  {type: "My Component", category: "other"},
  {color: "red" }
];

let res = myArray.reduce((acc, curr) =>
{
    Object.keys(curr).forEach(k =>
    {
        acc[k] = (acc[k] || []).concat(curr[k]);
    });
    return acc;
}, {});

res = Object.entries(res).map(([k, v]) => ({[k]: v.length > 1 ? v : v[0]}));

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Note, this approach will also work if your input objects have more then one pair of key/value.

Comments

0

Other answers look fine, here's a short alternative, also using Array.reduce and Object.entries:

const myArray = [{type: "My Application"}, {type: "My Component"}, {color: "red"}];

const withUniqueKeys = Object.entries(
  myArray.reduce((result, item) => {
    const [key, val] = Object.entries(item)[0];
    result[key] = result[key] ? [...[result[key]], val] : val;
    return result;
  }, {})
).map(([key, val]) => ({[key]: val}));

console.log(withUniqueKeys);

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.