1

I have an array of objects which looks like this:

[  
   {  
      "a":"alpha",
      "b":{  
         "x":true,
         "y":true
      }
   },
   {  
      "a":"beta",
      "b":{  
         "x":true,
         "z":true
      }
   }
]

I want to loop through this array to get a qnique list of all keys of 'b' alone. So, that my resulting array will be:

[x,y,z]

I tried the following:

const mykeys = myArray.map(item => Object.keys(item.b))

However, this only gves me: [[x,y], [y,z]]

How can I get the result as [x,y,z] instead.

4 Answers 4

1

Use Array#reduce to concatenate the arrays into single array. Then using spread operator with Set you can get unique items.

Set lets you to store unique values.

const myArray = [  
   {  
      "a":"alpha",
      "b":{  
         "x":true,
         "y":true
      }
   },
   {  
      "a":"beta",
      "b":{  
         "x":true,
         "z":true
      }
   }
]

const mykeys = myArray.map(item => Object.keys(item.b))
                      .reduce((a,b) => a.concat(b));
                      
const uniqueKeys = [...new Set(mykeys)];

console.log(uniqueKeys);

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

1 Comment

This works great, thanks! I am asusming that this will work, no matter how many objects we have in the initial array. Can you confirm?
1

You could take a dynamic approach by using a variable for the wanted key of the object and get all inner keys.

This approach uses a default object if the given key does not exist.

var data = [{ a: "alpha", b: { x: true, y: true } }, { a: "beta", b: { x: true, z: true } }],
    key = 'b',
    unique = [
        ...new Set(
            data.reduce((r, o) => [...r, ...Object.keys(o[key]) || {}], [])
        )
    ];

console.log(unique);

Comments

0

Here is the simple and much understanding way to achieve what you want.

var inputArray = [  
   {  
      "a":"alpha",
      "b":{  
         "x":true,
         "y":true
      }
   },
   {  
      "a":"beta",
      "b":{  
         "x":true,
         "z":true
      }
   }
];
var resArray = [];
inputArray.forEach((inputObj)=>{
  var keysForB = Object.keys(inputObj.b);
  keysForB.forEach((keyInB)=>{
    if(!resArray.includes(keyInB)){
       resArray.push(keyInB);
    }
  });
});

console.log(resArray);

Comments

0

You can use Set with array spread syntax to get the unique keys.

const myArray = [{"a":"alpha","b":{"x":true,"y":true}},{"a":"beta","b":{"x":true,"z":true}}],
      myuniquekeys =[...new Set([].concat(...myArray.map(({b}) => Object.keys(b))))];
      
console.log(myuniquekeys);

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.