Well, this is my response. results is a new empty array. address is my nested object in user
response.data.forEach(user => {
results.push({
id: user.id,
name: user.name,
address: user.address.number
})
})
This way I get undefined result from address object. So how can I access it correctly?
It's hard to answer without seeing some sample data but from the look of it, I would guess user.address.number is simply not defined in your data set. Why would you expect it is?
By the way, your combination of forEach and push could be simplified with map:
var results = response.data.map(user => ({
id: user.id,
name: user.name,
address: user.address.number
}));
Related
Let's say I have some code, like this:
const filter = {
address: 'India',
name: 'Aleena'
};
const users = [{
name: 'John Doe',
email: 'johndoe#mail.com',
age: 25,
address: 'USA'
},
{
name: 'Aleena',
email: 'aleena#mail.com',
age: 35,
address: 'India'
},
{
name: 'Mark Smith',
email: 'marksmith#mail.com',
age: 28,
address: 'England'
}
];
const filteredUsers = users.filter((item) => {
for (var key in filter) {
if (item[key] === undefined || item[key] != filter[key])
return false;
}
return true;
});
How can I dynamically update/change the filter object to allow users to choose which key:values to use in the filtering process? I know people normally use React for this kind of stuff, but I wondered if there was a "vanilla" way to do it.
Actually, filter does it for you already. Filter returns a new filtered array without mutating the original array.
"Users" is the original array. "FilteredUsers" is the newly created filtered array off users.
To clone/copy the original Users array above, you can do:
let clonedArray = [...Users]
The users array is a perfect candidate for this. Let's say you want to add all of the users ages together. It's pretty cool-simple.
1- function addAges(acc,ele) {return acc + ele.age}
2- Users.reduce(addAges, 0);
That'it. No console.log either. It'll returned the sum
here's a very basic example in CodeSandBox to get an idea of what to do.
I believe it meets the requirements of your question
https://codesandbox.io/s/vanila-js-dynamic-filter-6yhhe6?file=/src/index.js
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' }
I am working on the createGroup() functionality for my application.
And this is the data structure I have planned:
Groups(collection)
GroupID(document)
name: value,
description: value,
createdOn: value,
Members(subcollection)
userId1(document)
role: value,
joinedOn: value,
userId2(document)
role: value,
joinedOn: value,
GroupId(document)
...and so on...
I am trying to achieve this :
I was made the above structure manually in the console, but I don't know how to make it programmatically??
From what I have understood after reading through the docs, I can use transactions like this:
createGroup() {
var docRef = firestore()
.collection('Groups')
.doc();
firestore().runTransaction(transaction => {
return transaction.get(docRef).then(doc => {
transaction.set(docRef, {
name: this.name,
desc: this.desc,
createdOn: new Date(),
});
});
});
}
But I still can't figure out how to create a members sub-collection and add users to it, since we have only four methods to work with in transactions: set(), get(), delete() and update()
Please tell me how should I progress further??
Thank you.
Okay, I have this array pokemonColor=['name1', 'name2', 'name3']. How can I iterate trough this array and dynamically send http request so I can update state like this below? Because this what I am trying does not work, it creates a JavaScript object, but too many of them...
This is what I want:
this.state.pokemon:[
{name: name1, img: img1},
{name: name2, img: img2},
{name: name3, img: img3}
]
And this is how I am trying:
componentDidUpdate() {
// console.log(this.state.pokemonColor);
this.state.pokemonColor.forEach(pok => {
axios.get(`https://pokeapi.co/api/v2/pokemon/${pok}/`).then(res => {
// console.log(res.data.sprites.front_shiny);
this.setState({
...this.state,
pokemon: {
name: res.data.name,
img: res.data.sprites.front_shiny
}
});
});
});
// console.log(this.state.pokemon);
}
First of all - this.state.pokemon = [...] mutates the state directly. Your app may crash or at least you will receive a long, red error in your console.
Secondly - you don't have to destructure state inside setState function.
Thirdly - with every axios get request, you are overwriting pokemon field in your state. I'd suggest you to keep your pokemons inside array.
this.setState((prevState) => ({
pokemon: [
...prevState.pokemon,
{
name: res.data.name,
img: res.data.sprites.front_shiny,
},
],
});
Then you will be able to access your pokemons by referencing to this.state.pokemons, which will be an array of objects.
So I am trying to add a field to a user object right before I return it and the property is not being added for some reason. Any thoughts?
returnUser = function(userRes) {
console.log(">POST /returnuser< Returning user w/ userId: " + userRes.userId + " deviceToken: " + userRes.deviceToken);
return Location.findOne({
users: {
$elemMatch: {
user: userRes.userId
}
}
}, function(error, response) {
userRes.currentLocation = response;
console.log(userRes);
return res.send(userRes);
});
};
So in the returnUser function I am searching the DB for the user's current location, adding that to the userRes object and then returning it. But when I log the userRes object it doesn't contain that property. Any issue with my code? userRes currently looks like this:
{ _id: 1,
createTime: 1428477183281,
deviceId: '982f24khsd',
deviceToken: 'kjs398fskjjg5fb43ds323',
firstName: 'Cat',
lastName: 'Man',
email: 'cat#mandu.com',
__v: 0,
users: [],
locations: [],
lngLat: [] }
As it turns out, that userRes object is actually a mongoose model instance returned from a mongoose query which is not mutable.
To fix this you can preferably call lean() which will give you a plain JS object instead of a full model instance.
Or if you don't have access to the query you can do something like:
mutableUserRes = JSON.parse(JSON.stringify(userRes));
Which copies the whole object but it is now a simple JS object instead of a mongoose model instance.