How to push data into an object in javaScript? - javascript

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
}));

Related

how to convert an array to a array of objects with additional information in react using map when doing a POST api request

I'm new with react and I'm stuck at a problem, kindly help me.
array looks like this:
surveyors=[jj,kk]
The length of array can be variable i.e.there can be more values.
what i want to send in post api is:
data:[
{
name:"kk",
is_active:True,
company:26
},
{
name: "jj",
is_active:True,
company:26
}
]
I'm using postapi like this:
const postURL = moduleURL("url");
requests({
method: "post",
url: postURL,
data: [
{
name:"kk",
is_active:True,
company:26
},
{
name: "jj",
is_active:True,
company:26
}
],
})
.then((response) => {
console.log(response);
})
.catch((err) => console.log(err));
}
if there was a fixed data i could do it but since the data in array surveyor is variable i cannot fix it.
note- company here is the company id that i have stored in a variable and it will be same for every object in array and is_active will always be true.
var supervisor=["jj","kk"];
var result = supervisor.map(s => {return {name: s, is_active:true, company:26} });
console.log(result)
use map to create a new array of objects with extra attributes;
const supervisors = ["jj", "kk"];
const modifiedSupervisors = supervisors.map(item => ({name: item, is_active:true, company:26}));
now you can use this data in api call data: modifiedSupervisors,

From single array convert to an array of object with keys coming from a JSON response -JAVASCRIPT-

I am receiving a json response from an API call. I need to store its keys, and create an array of an object. I am intending to this array of an object is created dynamically no matter the keys of the response.
I've already got the keys like this:
const json_getAllKeys = data => {
const keys = data.reduce((keys, obj) => (
keys.concat(Object.keys(obj).filter(key => (
keys.indexOf(key) === -1))
)
), [])
return keys
}
That returned an array (using a sample json):
['name','username', 'email']
But I am trying to use that array to create an array of object that looks like this one
[
{
name: "name",
username: "username",
email: "Email",
}
];
I've been trying mapping the array, but got multiple objects because of the loop, and I need a single one to make it work.
keys.map(i=>({i:i}))
[
{ i: 'id' },
{ i: 'name' },
{ i: 'username' },
{ i: 'email' }
]
Any hint would be useful!
Thanks in advance :D
What you're looking for is Object.fromEntries, which is ECMA2019, I believe, so available in Node >=14 and will be provided as a polyfill if you employ babel.
I can't quite discern what your reduce should produce, but given the sample input, I would write
const input = ['name','username', 'email'];
const result = Object.fromEntries(input.map(name => ([name, name])));
// result == { name: 'name', username: 'username', email: 'email' }
You're definitely on the right track. One thing to remember is the map function will return the SAME number of output as input. So in your example, an array of 3 returns an array of 3 items.
For this reason, map alone is not going to give you what you want. You may be able to map => reduce it. However, here is a way using forEach instead. This isn't a strictly functional programming style solution, but is pretty straight forward and depending on use case, probably good enough.
let keys = ['name','username', 'email'] //you have this array
const obj = {}; // empty object to hold result
keys.forEach(i => {
obj[i] = i; // set the object as you want
})
console.log(obj); // log out the mutated object
// { name: 'name', username: 'username', email: 'email' }

Create an object or associative array with elements of an existing array and the result of a callout for each element

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);

React -> Saving in one state only the 'id' and 'name' of the object

Good evening, I have an objet array coming from my API, and would like to keep in one state only the 'id' and 'name' of the object. Does anybody have any idea how to do it?
state = {
countries: [//{id: name}, {id: name}, {id: name}]
};
componentDidMount() {
api.get('/countries').then(res => {
// ??
})
}
Assuming that the response from the API is an array of object, you can simply loop through the response to extract only the fields (id and name) that you need, and update your component's state with the new data.
componentDidMount() {
api.get('/countries').then(res => {
const countries = res.map((country) => ({
id, name,
}));
this.setState({
countries
});
});
}

How to save the objects uid when I push the data in firebase database list, using javascript

I want to save the uid when I push new data in Firebase database. This is possible not for auth users but for data objects.
For example, I want this object schema:
"-Kdsfdsg555555fdsgfsdgfs" : { <------- I want this id
Id : "Kdsfdsg555555fdsgfsdgfs", <--- How to put that inside
name : "A",
time_updated : "6/6/2017"
}
Is any way how to get this id and pushed inside the object?
My code is as follows:
categories: FirebaseListObservable<any[]>;
this.categories = this.db.list('/categories') as FirebaseListObservable<Category[]>;
addCategory(category: any) {
return this.categories.push(category).then( snap => {
this.openSnackBar('New category has been added', 'ok');
}).catch(error => {
this.openSnackBar(error.message, 'ok');
});
}
There are two ways to use Firebase's push() method:
By passing in an argument, it will generate a new location and store the argument there.
By passing in no arguments, it will just generate a new location.
You can use the second way of using push() to just get the new location or its key:
addCategory(category: any) {
var newRef = this.categories.push();
category.Id = newRef.key;
newRef.set(category).then( snap => {
this.openSnackBar('New category has been added', 'ok');
}).catch(error => {
this.openSnackBar(error.message, 'ok');
});
}
But note that it's typically an anti-pattern to store the key of an item inside that item itself too.

Categories

Resources