this.crudService.get('user.php?mode=test')
.subscribe((data:any) => {
{ for (var key in data) { this[key] = data[key]; } };
}
);
This use to work on angular 7 now on angular 13 i get this error (look image)
In template i was using the values for example in json string was and array and i had users, in template was {{users}} , {{posts}} etc.. now the this[key] give error , please help me out its very important can't find solution
i'll show an example code, and then applied to your code:
Example
// creating global variables to receive the values
users: any = null;
posts: any = null;
// simulating the data you will receive
data: any[] = [
{users: ['user1', 'user2', 'user3']},
{posts: ['post1', 'post2', 'post3']}
];
getCrudService() {
// access each object of the array
this.data.forEach(obj => {
// getting keys name and doing something with it
Object.keys(obj).forEach(key => {
// accessing global variable and setting array value by key name
this[String(key)] = obj[String(key)]
})
})
}
Apllied to your code
this.crudService.get('user.php?mode=test').subscribe((data:any) => {
data.forEach(obj => {
Object.keys(obj).forEach(key => {
this[String(key)] = obj[String(key)]
});
});
});
I hope it helped you, if you need help, just reply me.
I'm new to JS and trying to figure out how to iterate through a json array and return only a subset of elements. Specifically I would like to know how to return only the 'first_name' and 'last_name' from the Mock data in the attached code snippet. It seems like it should be straightforward but I'm scratching my head.
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}]
people.forEach(person => {
for (let key in person) {
console.log(`${key} => ${person[key]}`);
}
Use the element names
people.forEach(person => {
console.log(JSON.stringify(person) + "\n");
console.log(person["first_name"], person["last_name"], "\n");
});
Produces this output:
{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"}
Talbert Kohnert
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"}
Ruthie McKleod
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}
Lenore Foister
You can try Object destructuring assignment of ES6 to achieve the requirement.
Working Demo :
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}];
let res = people.map(({first_name, last_name}) => first_name + ' ' + last_name);
console.log(res);
There are numerous way of achieving this output. One of most frequently used method is using map() of es6.
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}]
//by map method
people.map((person,index)=>{
console.log(`${person.first_name} ${person.last_name}`)
})
// by forEach
people.forEach(person => {
console.log(`${person.first_name} ${person.last_name}`)
}
you can achieve this by using the map function.
map lets you iterate over each item in the array and return a new value for each iteration while returning a new array, so for your case:
let people = [
{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}
]
const newArray = people.map((person) => {
return {
first_name: person.first_name,
last_name: person.last_name
}
})
console.log(newArray)
here you get a new array with just the properties you need.
I need to map over an array in my state and assign the returned value to another property in my state.
I then need to call a function using the value of the updated property as a parameter, wait for this function to complete and then move on to the next item in my array map method before repeating the process.
The problem is that I think my function is being run before the state has been updated through each iteration of my arr.map method.
I think I need to utilise the componentDidUpdate() method before running my function, but I am not sure how to implement that in this scenario.
Simpler to explain through code example, see below (edited for simplicity):
state = {
a: [ {name: 'some string'}, {name: 'some string'}..... ],
b: '' // empty string
}
// when button is clicked, this function is run
myFunc() {
this.state.a.map( (item) => {
this.setState({
b: item.name
})
mySecondFunc()// perform next part of the loop
})
}
mySecondFunc() {
alert( this.state.b )
}
The alert in mySecondFunc() does not return anything, it is not being updated before the function is run.
What I need to happen is that the map will get the first item from my states 'a' array, assign it to state 'b' and run mySecondFunc().
I need to wait for state to be updated, before calling mySecondFunc, and then wait for mySecondFunc() to end its function before the map gets the next item from my state's 'a' array and calls mySecondFunc again.
This is the part that I cannot figure out.
try this
state = {
a: [ {name: 'some string'}, {name: 'some string'}..... ],
b: '' // empty string
}
// when button is clicked, this function is run
myFunc(){
this.state.a.map(async(item) => {
await this.setState({
b: item.name
},async () => {
await mySecondFunc()// perform next part of the loop
})
})
}
mySecondFunc() {
alert( this.state.b )
}
//OR
myFunc(){
this.state.a.map(async(item) => {
await mySecondFunc(item)
})
}
mySecondFunc(item) {
alert( item )
}
What I have understood from the problem description is that the goal here is to pass b's value sequentially to mySecondFunc . According to my understanding of the problem, I have modified your code :
myFunc() {
this.state.a.map( (item) => {
this.setState( (prevState) => {
const modifiedName = item.name;
this.mySecondFunc(modifiedName);
return {
b: modifiedName
}
});
});
}
mySecondFunc(name) {
alert( name );
}
Now I would like to get a variable from if inside same function as if like below.
renderItemBox() {
const { store } = this.props;
const currentScreen = this.props.navigation.state.routeName;
AsyncStorage.getItem('openingGenre')
.then((openingGenreValue) => {
if (currentScreen === 'EachShopGenreScreen') {
if (openingGenreValue === 'food') {
const items = this.store.restourantStore.Items;
} else {
Alert.alert('予期せぬ不具合が発生いたしました。再度お試し下さい');
}
});
return items.map((value, index) => (
//////
)
However, this code is not working, I cannot get "items" from IF on items.map~~~~
Why this is happening?
Could someone help me.
You need to declare items using let as an empty array in the function scope then do your if statement.
Or at least that's one way of doing it.
Btw this is more of a JavaScript question.
On submitting a form with some updated values, I need to update the state to reflect these changes, but I am new to Immutable.js and am unsure how to do so.
Is it possible to pass a function as a 2nd argument to set or update to update values based on certain criteria.
I have a function which receives state and an array of objects called values. The data in values looks like this:
[
{
key: 'name',
value: 'fred'
},
{
key: 'height',
value: '201'
},
{
key: 'weight',
value: '78'
}
]
I need to map over this data, and the state list, and update the corresponding values in the state list with the values array.
How can I do this. I have put together a function which the Reducer calls to update the state with the new data, but unsure exactly how to get the end result
function updateValue(state, values = []) {
const items = state.get('items').map((i) => {
const key = i.get('key');
values.map(v => {
if (v.key === key) {
return state.update('value', v.value);
}
})
});
return state.update('items', /* Can I use a function here to replace the code above.. to update all of the items in the state List that correspond to the items in the measurements array (which have new values) */);
}
Thank you very much.
Update
Tried the following, but getting the error: Expected [K, V] tuple: i
function updateValue(state, values = []) {
const items = state.get('items').map((i) => {
const key = i.get('key');
values.map(v => {
if (v.key === key) {
return state.update('value', v.value);
}
})
});
return state.update('items', items);
}
More details on the error from Immutable:
function validateEntry(entry) {
if (entry !== Object(entry)) {
throw new TypeError('Expected [K, V] tuple: ' + entry);
}
}
You can use 'merge' to return new object:
return state.merge({
items: values,
});