My frontend request form request get me this
req.body {
name: ["abc","ggg"],
class: ["A","B"],
bloodGroup: ["A+","B-"]
}
I had try will my code to solve the problem like this
let arr = [];
req.body.name.forEach((item, index)=>{
arr.push({
name: item,
class: req.body.class[index],
bloodGroup: req.body.bloodGroup[index]
})
})
return arr;
Is there any other way like dynamically, I will pass only my request and it will return me objects of these data
this is sample req.body there will be multiple more data in each key
name, class, bloodGroup
ex:
name ["a","b","c",...] so on...
class ["ab","bc","dc",...] so on...
bloodGroup ["a+","b+","c-",...] so on...
We can do an Array.map on the first property of the request body.
We then use Object.entries on req.body and map it to return only the correct entry for each index. We then use Object.fromEntries() to create each object.
This means that however many properties are present on req.body, they will be present on the result objects.
const req = {
body: {
name: ["abc","ggg", "ccc"],
class: ["A","B", "C"],
bloodGroup: ["A+","B-", "C-"],
height: [175, 182, 190]
}
}
const arr = Object.values(req.body)[0].map((item, index) => {
const entries = Object.entries(req.body).map(([key, properties]) => ([key, properties[index]]));
return Object.fromEntries(entries);
});
console.log(arr);
Related
I have 2 Arrays.
The Array "people" just holds basic information of some people.
The Array "subscriptions" has a lot of different subscriptions to games.
I want to have have an Array, where I can sort of have an Overview of what game subscriptions each person has. This is not real code I use, I am just trying to get used to JavaScript.
an example Element of an Array called people:
{"number":4251,"name":"Alex","surname":"Scott"}
an example Element of an Array called subscriptions:
{"number":4329,game:"Tetris"}
I want to make a new new Array with the following format:
person: (people[i]), subscriptions: [(subscriptions[j], subscriptions[j+k], ...)]
What I tried:
const array3 = people.map(x => {"person": x , "subscriptions": subscriptions.filter(y => y.number === x.number)});
It get this Error:
SyntaxError: Unexpected token :
How can I insert multiple key value pairs in in these Objects?
This happens because your argument in the map is interperting the { as opening bracket of the method body.
const arr = [{some: 1, object: 2}, {some:3, object:4}]
arr.map((o) => {original: o, cool: 'yes'})
To resolve this you have to explicitly return the object or add additional parenthesis to let the interperter know that this is not the method body:
const arr = [{some: 1, object: 2}, {some:3, object:4}]
const mapped = arr.map((o) => {return {original: o, cool: 'yes'}})
console.log(mapped)
const arr = [{some: 1, object: 2}, {some:3, object:4}]
const mapped = arr.map((o) => ({original: o, cool: 'yes'}))
console.log(mapped)
I hope this helps!
In your original code there is a syntax error, when it comes to the mapping part. Either you go with the long version of this command or, since you directly want to return the element, you can use the short version:
const people = [{"number":4251,"name":"Alex","surname":"Scott"}, {"number": 4329, "name":"Mr", "surname": "Tetri"}]
const subscriptions = [{"number":4329,game:"Tetris"}, {"number":4329, game:"Solitaire"}, {number: 4251, game: "Tetris"}]
// using an anonymous function including full body
const arrayLongVersion = people.map(x => { return {"person": x , "subscriptions": subscriptions.filter(y => y.number === x.number)} });
// using an anonymous function with direct return of elements
const arrayShortVersion = people.map(x => ({person: x , subscriptions: subscriptions.filter(y => y.number === x.number)}))
Here you go
const people = [
{"number":1,"name":"Alex","surname":"Scott"},
{"number":2,"name":"John","surname":"Anderson"},
{"number":3,"name":"Jacob","surname":"Sanderson"},
{"number":4,"name":"Lionel","surname":"Messi"},
{"number":5,"name":"Cristiano","surname":"Ronaldo"}
];
const subscriptions = [
{"number":1,game:"Tetris"},
{"number":2,game:"Super Mario"},
{"number":3,game:"Fortnite"},
{"number":4,game:"FIFA"},
{"number":5,game:"Zelda"}
];
const peopleSubscriptions = people.map(person => {
return {
...person,
subscriptions: subscriptions.filter(sub => sub.number === person.number)
}
});
console.log(peopleSubscriptions);
Background of my issue:
To start I had an array of objects each containing a user-ID called entries. I had to make an api call using the id inside each of those object to get the users full profile containing their fullName. I was able to map over the results of the api call to get a list of all users that had matching id's to the initial list I started with and with that I also pulled out their fullName this variable is labeled matches. So now I have the initial list [array] of userID's entries, along with a list of arrays of all the ID matches I found inside that list from my api call matches this list of arrays contains the ID and a Name.
What I am trying to do now is map over the entries and matches to compare userID's and if a match is found then I want to insert the name inside matches into the entry the match is found in based on the index. However I am not sure how to properly insert a key value pair inside of and object based on index or if im approaching this the correct way. Here is my code:
useEffect(() => {
const loadAllProviders = async () => {
//TODO: Make conditional if entries exists
try {
//get all providers
const results = await api.Providers.listnoAudit({ scope: "all" });
const allProviders = results.items;
//map over the entries to get providerId's out
const providerIDs = entries.map((entry) => entry.createdBy);
//map over response to get out provider names and id's
const idName = allProviders.map((provider) => [provider.id, provider.fullName]);
//find if any returned providers have matching ids to the ones in entries
const matches = idName.filter((match) => providerIDs.includes(match[0]));
//TODO: map over entries
// if matches[0] = entries.createdby then
//push matches[1] (name) into the object at the index where match occurs
entries.map((entry, idx) => {
matches.map((provider) => {
if (entry.createdBy === provider[0]) {
let en = {...entry, fullName: provider[1]}
}
})
});
} catch (err) {}
};
loadAllProviders();
}, [entries]);
Inside my if statement youll see my attempt to add the fullName to the entry using the spread operator but Im not sure how to actually replace the old object with the new object. When I console out en, I get the items that have been modified... I am pretty new to coding and any advice would be helpful.
You can probably reduce your allProviders list to get what you want. See the following example.
let allProviders = [
{id: 1, name: "Amy"},
{id: 2, name: "Kamala"},
{id: 3, name: "Stacy"},
{id: 4, name: "Sunil"}
]
let entries = [{createdBy: 2}, {createdBy: 4}]
let providerIds = entries.map(e => e.createdBy)
let result = allProviders.reduce((matches, provider) => {
if(providerIds.includes(provider.id)) {
matches.push({ ...provider, createdBy: provider.id})
}
return matches;
},[])
console.dir(result)
This is in the context of a node express route. I receive a get request with a query param that is a list of IDs. Now I need to make a call-out for each ID and store the result of the callout in an array or object. Each element of the first array (containing the IDs) need to be mapped to its corresponding result from the call-out. I don't have a way to modify the endpoint that I'm hitting from this route so I have to make single calls for each ID. I've done some research and so far I have a mixture of code and sudo code like this:
const ids = req.query.ids;
const idMembers = Promise.all(ids.map(async id => {
// here I'd like to create a single object or associative array
[ id: await callout(id); ]
}));
When all promises resolved I need the final result of idMembers to be like: (The response will be an object with nested arrays and objects I've just simplified it for this post but I need to grab that from the res.payload)
{
'211405': { name: 'name1', email: 'email1#test.co' },
'441120': { name: 'name2', email: 'email2#test.co' },
'105020': { name: 'name3', email: 'email4#test.co' }
}
Oh and of course I need to handle the callout and the promise failures and that's when my lack of experience with javascript becomes a real issue. I appreciate your help in advance!!
Some extra thought I'm having is that I'd have to map the results of the resolved promises to their id and then in a separate iteration I can then create my final array/object that maps the ids to the actual payloads that contain the object. This is still not answering any of my questions though. I'm just trying to provide as much information as I've gathered and thought of.
Promise.all returns an array of results (one item per each promise).
Having this temporary structure it is possible to build the needed object.
const arrayOfMembers = Promise.all(ids.map(async id => {
// ...
return { id, value: await callout(id) } // short syntax for { id: id, value: ... } (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer)
}));
// arrayOfMembers = [
// { id: 211405, value: { name: 'name1', email: 'email1#test.co' } },
// ...
// ]
In pure JS it can be done with for loop or .forEach() call to iterate:
const res = {};
arrayOfMembers.forEach(el => {
const { id, value } = el;
res[el] = value;
});
or by using a single reduce() call
const res = arrayOfMembers.reduce((accumulator, el) => {
const { id, value } = el;
return { ...accumulator, [id]: value };
}, {});
in both cases res will be:
// res = {
// '211405': { name: 'name1', email: 'email1#test.co' },
// ...
// }
P.S.
There is a handy library called lodash. It has tons of small methods for data manipulation.
For example, _.fromPairs() can build an object from [[key1, value1], [key2, value2]] pairs.
As you mentioned you have lodash, so I think the following should work:
const arrayOfKeyValuePairs = Promise.all(ids.map(async id => {
// ...
return [ id, await callout(id) ] // array here so it matches what fromPairs needs
}));
const res = _.fromPairs(arrayOfKeyValuePairs);
I am still learning things. Here I am trying to send data as an object to my end user. I succeeded in sending it as an array but failing to send as an object can you help me here, please.
I need data as an object data{}. This is in nodeJs.
let data = [];
students.map(student => {
data.push({
Name: payload.name,
stdId: payload.Id
});
});
You can only return an object and map will by itself will create & return an array of objects
let data = students.map(student => {
return {
Name: payload.name,
stdId: payload.Id
}
});
As you are using Array.map, you can simply use it to return the newly created object.
let data = students.map(student => ({
Name: payload.name,
stdId: payload.Id
}));
I am trying to assign clone/merge object, that has array where id matches or add to an end:
newState = Object.assign({}, state, {
data: {
newest: {
result: action.payload.result,
list: action.payload.items,
request: action.payload.items
},
itemList: [
...state.data.itemList,
{
id: action.payload.id,
list: action.payload.items,
request: action.payload.items
}
]
}
});
In this case ...state.data.itemList is an array with objects where I want to find an existing object with ID and merge list + request nested objects. However, if there is no object with that ID I want to add it to the list.
Current approach always adds it to the end, which of course is not what I want.
Thanks.
Don't feel pressured into making the new state in one operation. Here would be my implementation. I would check my array for the current id using Array#some. Here are some fun ES6 tricks too.
const newState = {...state}
const {result, items, id, items} = action.payload
const data = {newest: {result, list: items, request: items}}
const hasId = newState.data.itemList.some(item => item.id === id)
if (!hasId) {
newState.data.itemList.push({id, list: items, request: items})
}
return {...newState, data}