This is my model class. I have to map the values from array to respective ngModel checking the title and pushing the result in ngModel value.
In component file
export class demoModel{
demo1:string
demo2:string
}
demo=new demoModel()
var data= [{title:"demo1",result:1},{title:"demo2",result:2}]
for (const iterator of this.data) {
console.log(iterator)
//works upto here
for (const key of Object.keys(this.demo)) {
this.demo[key]=iterator.result;
}
}
IN HTML
<input [(ngModel)]="demo1">
<input [(ngModel)]="demo2">
How to achieve this in angular?
I tried using Object.keys to map the values but it is not working.
CodePudding user response:
Try mapping the data and the object's key , if data.title matches with the object's key , assign the data.result to the object's key.
export class demoModel {
demo1: string = '';
demo2: string = '';
}
demo = new demoModel();
var data = [{
title: "demo1",
result: 1
}, {
title: "demo2",
result: 2
}]
this.data.map(x => {
Object.keys(this.demo).map(y => {
if (y == x.title) {
this.demo[y] = x.result;
}
})
})`
CodePudding user response:
Mapping values are not related to Angular. If you want to map the values, you need to create some functions to work on them.
First, create a function to get the response and iterate with it. Next, declare a function that takes the key and the value to compare it and assign it to the object.
You can write a better version using Object.keys
if the name "demo1" and "demo2" change or add new properties.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
const response = [
{
title: 'demo1',
result: 1,
},
{
title: 'demo2',
result: 2,
},
];
class demoModel {
demo1: string;
demo2: string;
}
function getValue(value, entity, key) {
if (entity[key] == null) {
return value.title === key ? value.title : null;
} else {
return entity[key];
}
}
function mappingValues(value) {
let entity = new demoModel();
value.forEach((v) => {
entity.demo1 = getValue(v, entity, 'demo1');
entity.demo2 = getValue(v, entity, 'demo2');
});
return entity;
}
const mappedResponse = mappingValues(response);
console.log(mappedResponse);