1

I have this kind of object:


{
    "John":[
        {
            "address":"xxx1",
            "city":"yyy1"
        },
        {
            "address":"xxx2",
            "city":"yyy2"
        }
        
    ],
    
    "Doe":[
        {
            "address":"aaaa1",
            "city":"aaa1"
        }
        
    ],

    "Smith":[
        {
            "address":"bbb1",
            "city":"bbb1"
        }
    ],

}

What I try to achieve is to reduce this object so it look like this:

[
{
    "name":"John",
    "address":"xxx1",
    "city":"yyy1"
},
{
    "name":"John",
    "address":"xxx2",
    "city":"yyy2"
},
{
    "name":"Doe",
    "address":"aaaa1",
    "city":"aaaa1"
},
{
    "name":"Smith",
    "address":"bbb1",
    "city":"bbb1"
}
]

But I'm sure that the same thing can be done somehow by using the ES6 array.reduce. Can you help me? I looked at JS (ES6): Reduce array based on object attribute but I can't figure it out.

const modifiedData = Object.entries(data).reduce(function (acc, [key,value]) {
      const personName = key;
      return [
        ...acc,
        {
          Agent: personName ,
          adress: value.adress

        },
      ];
    }, []);
1
  • Use .flatMap() to iterate over the result of Object.entries() and in the callback use .map() to create new objects with the given properties + the name. Commented Apr 14, 2021 at 9:43

3 Answers 3

1

You can achieve this using reduce.

const obj = {
  John: [
    {
      address: "xxx1",
      city: "yyy1",
    },
    {
      address: "xxx2",
      city: "yyy2",
    },
  ],

  Doe: [
    {
      address: "aaaa1",
      city: "aaa1",
    },
  ],

  Smith: [
    {
      address: "bbb1",
      city: "bbb1",
    },
  ],
};

const result = Object.entries(obj).reduce((acc, [key, arr]) => {
  const collection = arr.map((a) => ({ name: key, ...a }));
  acc = [...acc, ...collection];
  return acc;
}, []);

console.log( result );

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

Comments

0

The simple way like this.

const data = {"John":[{"address":"xxx1","city":"yyy1"},{"address":"xxx2","city":"yyy2"}],"Doe":[{"address":"aaaa1","city":"aaa1"}],"Smith":[{"address":"bbb1","city":"bbb1"}],};;

const result = Object.entries(data).flatMap(([key, values]) => 
                                   values.map(o => ({name: key, ...o})));
console.log(result);

1 Comment

@Nguyen, Your solution is good too, but decpk's solution was first and it fits my needs so I accepted his answer. Thanks!
0

If you want to do it using Array.prototype.reduce, you can do something like this:

const input = {
  "John": [{
      "address": "xxx1",
      "city": "yyy1"
    },
    {
      "address": "xxx2",
      "city": "yyy2"
    }

  ],
  "Doe": [{
      "address": "aaaa1",
      "city": "aaa1"
    }

  ],
  "Smith": [{
    "address": "bbb1",
    "city": "bbb1"
  }],
}

// 1. Using Object.keys()
const output1 = Object.keys(input).reduce((acc, person) => {
  input[person].forEach(item => {
    acc.push({ name: person, ...item })
  })
  return acc;
}, []);
console.log('output1:', output1)

// 2. Using Object.entries()
const output2 = Object.entries(input).reduce((acc, [key, value]) => {
  value.forEach(item => {
    acc.push({ name: key, ...item })
  });
  return acc;
}, [])
console.log('output2:', output2);

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.