Michael Vasilevsky
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}`]);
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}`,
}]);
Can I use map to create an array of objects and if so, what is the syntax?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
@Flabio Gates: you got me there - the below works:
@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.
myPeopleArray = data.d.results.map(Person => ({
"ID": `${Person.Id}`,
"Name": `${Person.FullName1}`,
"Department": `${Person.Department1Id}`,
}));
@Julian Hansen: console.log(data.d.results
ASKER
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?
ASKER
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
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.
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?
Open in new window