const arrayObj = [{
id: 123,
country: "IND"
value: ""
},
{
id: 153,
country: "AUS"
value: ""
},
{
id: 183,
country: "FRA"
value: ""
}
];
const value = [100, 200, 300];
I need to map value array into the correspondent value property in array of object
So, my array of object look like this
[
{
id: 123,
country: "IND"
value: 100
},
{
id: 153,
country: "AUS"
value: 200
},
{
id: 183,
country: "FRA"
value: 300
}
]
const arrayObj = [{
id: 123,
country: "IND"
value: ""
},
{
id: 153,
country: "AUS"
value: ""
},
{
id: 183,
country: "FRA"
value: ""
}
];
const value = [100, 200, 300];
I need to map value array into the correspondent value property in array of object
So, my array of object look like this
[
{
id: 123,
country: "IND"
value: 100
},
{
id: 153,
country: "AUS"
value: 200
},
{
id: 183,
country: "FRA"
value: 300
}
]
Share
Improve this question
edited Jul 21, 2020 at 6:57
Yves Kipondo
5,6531 gold badge21 silver badges33 bronze badges
asked Jul 21, 2020 at 5:59
PiyushPiyush
851 silver badge5 bronze badges
2 Answers
Reset to default 4You can map over the arrayObj
and use the index param to get corresponding values from value
array.
const arrayObj = [
{
id: 123,
country: "IND",
value: "",
},
{
id: 153,
country: "AUS",
value: "",
},
{
id: 183,
country: "FRA",
value: "",
},
];
const value = [100, 200, 300];
const result = arrayObj.map((item, index) => ({...item, value: value[index]}));
console.log(result);
// If you don't want to create new array, you can use forEach
arrayObj.forEach((item, index) => {
item.value = value[index];
});
First of all you have to format very wall each object into the arrayObj
variable, items in an array are separated by ,
like this [1,2,3]
and it's the same for every key:value
pair in an object {item1: "itemvalue", item2: "itemvalue2"}
const arrayObj = [{
id: 123,
country: "IND",
value: ""
},
{
id: 153,
country: "AUS",
value: ""
},
{
id: 183,
country: "FRA",
value: ""
}
];
const value = [100, 200, 300];
const newArrayObj = arrayObj.reduce((acc, current, index) => {
return acc.concat({...current, value: value[index]});
}, []);
console.log(newArrayObj);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745132232a4613026.html
评论列表(0条)