Link to home
Start Free TrialLog in
Avatar of Michael Vasilevsky
Michael VasilevskyFlag for United States of America

asked on

Use JavaScript .map to Create an Array of Objects

I can create an array of arrays from ajax results using:
myPeople = data.d.results.map(Person => [`${Person.Id}`, `${Person.FullName1}`, `${Person.Department1Id}`]);

Open in new window

but I want to create an array of objects instead; the following gives me an array of arrays of objects:
            myPeopleArray = data.d.results.map(Person => [{
                "ID": `${Person.Id}`,
                "Name": `${Person.FullName1}`,
                "Department": `${Person.Department1Id}`,
            }]);

Open in new window

Can I use map to create an array of objects and if so, what is the syntax?
ASKER CERTIFIED SOLUTION
Avatar of Flabio Gates
Flabio Gates

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Julian Hansen
I don't understand this
myPeople = data.d.results.map(Person => [`${Person.Id}`, `${Person.FullName1}`, `${Person.Department1Id}`]);

Open in new window

Is data.results not already an array of objects?
You are mapping over data.results with each array element being put into Person and then accessing
Person.id
Person.FullName1
Person.Department1Id

Which is an object.

What does your incoming source data look like?
What do you get from this?
console.log(data.results);

Open in new window

Avatar of Michael Vasilevsky

ASKER

@Flabio Gates: you got me there - the below works:

myPeopleArray = data.d.results.map(Person => ({
           "ID": `${Person.Id}`,
           "Name": `${Person.FullName1}`,
           "Department": `${Person.Department1Id}`,
}));

Open in new window


@Julian Hansen: console.log(data.d.results) returns an array of objects, just like I want, but with a lot more attributes than I care about (see below). I'm using map to extract just the values I want to assign them to my attributes.

User generated image
Thank you!
but with a lot more attributes than I care about (see below). I'm using map to extract just the values I want to assign them to my attributes.
Sorry but this does not make sense. You query a service, get a result (which contains more data than you need) go through a process of extracting the data you do need and then go through another process of consuming the data? Why not just feed the response straight to where it is needed?
Hi Julian, I'm using the data a few places on the site, so I think it makes sense to query the backend once, move the data into an array, and then consume it where I need it. This is SharePoint Online again so I'm only able to code the client-side and I'm looking to reduce the number of REST API calls.

Thanks for the input!

MV
Ok just note you can move the data returned as is - there is no need to refactor it. But I will leave it there.