1

I'm having the JSON like this i need to group this JSON with all the keys in JSON object and value should in array (excluding duplicates).

var people = [
    {sex:"Male", name:"Jeff"},
    {sex:"Female", name:"Megan"},
    {sex:"Male", name:"Taylor"},
    {sex:"Female", name:"Madison"}
];

My output should be like

{"sex":["Male","Female"],"name":["Jeff","Megan","Taylor","Madison"]}

how we can able to achieve this

2 Answers 2

2
function getValues(array) {
    var result = {};
    array.forEach(obj => {
        Object.keys(obj).forEach(key => { 
        if(!Array.isArray(result[key])) 
            result[key] = [];
        result[key].push(obj[key]);
        })
    })
return result;
}
Sign up to request clarification or add additional context in comments.

2 Comments

typeof cannot be used to check if something is an array. Just check if typeof result[key] === "undefined" or result[key] instanceof Array or Array.isArray() etc
My mistake, forgot about that.
1

You could use the Array.reduce() method to transform your array into a single object:

var people = [
    {sex:"Male", name:"Jeff"},
    {sex:"Female", name:"Megan"},
    {sex:"Male", name:"Taylor"},
    {sex:"Female", name:"Madison"}
];

const transformed = people.reduce((acc, e) => {
  Object.keys(e).forEach((k) => {
    if (!acc[k]) acc[k] = [];
    if (!acc[k].includes(e[k])) acc[k].push(e[k]);
  });
  return acc;
}, {});

console.log(transformed);

If for one of the object keys (sex or name in this case) a value array does not exist, it is created. Before a value is pushed into any of the value arrays, it is verified that it is not already present in that array.

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.