0

I have an array of objects, I'm trying to loop through them via map function and create an output as follows:

Desired output

dataSet = [
 [John, Doe, Sales],
 [Jane, Doe, HR], 
 [Jack, Doe, Manager]
]

My array of objects:

[[object],[object],[object]]

Here is what I have tried so far:

 users.map((item) => {
  dataSet.push(item.profile.firstName, item.profile.role)
 })

However my output:

["John","Jane","Jack"]

How can I push each loop into new array?

Thanks

3
  • How are you getting that output? What is the actual input? It looks like there should be 6 items in the output array, since you're pushing 2 items per iteration. Commented Apr 22, 2017 at 3:37
  • As a sort of aside, if you are not using the return value of .map() then you're using .map() incorrectly and should be using .forEach() instead. Commented Apr 22, 2017 at 3:41
  • is your array of objects an array of arrays containing objects? [[{...}],[{...}]], or an array of objects [{...},{...}] Commented Apr 22, 2017 at 3:42

4 Answers 4

2

Actually, you are pretty close. Just make what you want to push an array. Try the following codes:

users.forEach((item) => {
  dataSet.push([item.profile.firstName, item.profile.lastName, item.profile.role]);
});
Sign up to request clarification or add additional context in comments.

1 Comment

@4castle you dare absolutely correct. I've updated it
1

Assuming your original data looks like:

data: [
    ...
    {
        profile: {
            firstname: "John",
            lastname: "Doe",
            role: "Sales"
        }
    },
    ...
];

You could do this:

var dataSet = data.map((person) => {
    let profile = person.profile;
    return [
        profile.firstname,
        profile.lastname,
        profile.role
    ];
});

Hope this helps!

Comments

1

When you are mapping the array of objects you should just return an array with the values you want.

const john = { firstName: 'John', lastName: 'Doe', role: 'Sales' }
const jane = { firstName: 'Jane', lastName: 'Doe', role: 'HR' }
const jack = { firstName: 'Jack', lastName: 'Doe', role: 'Manager' }
const users = [ john, jane, jack ]
const dataSet = users.map(user => ([ user.firstName, user.lastName, user.role ]))
console.log(dataSet)

Comments

0

You can do this in a more generic way by allowing for any number of properties on the object using map, e.g.

dataset = [
           {firstName: 'John', lastName: 'Doe', role: 'Sales'},
           {firstName: 'Jane', lastName: 'Doe', role: 'HR'},
           {firstName: 'Jack', lastName: 'Doe', role: 'Manager'}
          ];

var result = dataset.map(obj => Object.keys(obj).map(key => obj[key]));

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.