1

I have an array who look like this:

tab [
    0: {
        firstName: John,
        lastName: Doe,            
        situation: married,
        familyMembers: 5,
    }
    1: {
        firstName: Jack,
        lastName: Daniel,
        situation: single,
        familyMembers: 6,
    }
]

I need something like this:

{
    [John]: {[Doe]: 5,
    [Jack]: {[Daniel]: 6,
}

I tried something like this:

tab.map((item) => {
    return (
        {[item.firstName]: {[item.lastName]: item.familyMembers}}
    )
})

But even without considering that I have an array instead of an object the result look like this:

[
    0: {
        [John]: {[Doe]: 5,
    }
    1: {
        [Jack]: {[Daniel]: 6,
    }
]

Any suggestion here will be appreciate I tried using reduce but as I probably don't use it well it make really bad result.

2 Answers 2

1

Assuming, you wnat the names as keys, yxou could build the entries and from it the object.

var tab = [{ firstName: 'John', lastName: 'Doe', situation: 'maried', familyMembers: 5 }, { firstName: 'Jack', lastName: 'Daniel', situation: 'single', familyMembers: 6 }],
    result = Object.fromEntries(tab.map(({ firstName, lastName, familyMembers }) =>
        [firstName, { [lastName]: familyMembers }]
    ));

console.log(result);

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

Comments

1

map() always returns an array of the results of the function.

You can use reduce() instead

var tab = [{
    firstName: 'John',
    lastName: 'Doe',
    situation: 'maried',
    familyMembers: 5,
  },
  {
    firstName: 'Jack',
    lastName: 'Daniel',
    situation: 'single',
    familyMembers: 6,
  }
];
var result = tab.reduce((obj, item) => {
  obj[item.firstName] = {
    [item.lastName]: item.familyMembers
  };
  return obj;
}, {});
console.log(result);

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.