I would like to know how to compare and change the array value by object value in javascript
I have a arrobj
and obj
in which if arrobj value city
and obj key saame the change the city vaue in arrobj,
var arrobj =[
{
"id":1, "name": "xyz", "city":"IN",
"id":2, "name": "abc", "city":"CA",
"id":3, "name": "jon", "city":"MY",
"id":4, "name": "om", "city":"CH",
"id":5, "name": "ken", "city":"JP",
}
]
var obj={
"CA": "Canada",
"MY": "Myanmmar",
"IN": "India"
}
Expected Output
[
{
id:1, name: "xyz", city:"India",
id:2, name: "abc", city:"Canada",
id:3, name: "jon", city:"Myanmmar",
}
]
var arr1 = [];
var result = arrobj.map(e=>{
return Object.keys(obj).map(i=>{
if(e.city===i){
arr1.push({
...e,
city:i
})
}
})
})
console.log(arr1)
Using Array#map
, you can iterate over arrobj
and update city
if it has a value in obj
:
const arrobj = [ { id:1, name: "xyz", city:"IN" }, { id:2, name: "abc", city:"CA" }, { id:3, name: "jon", city:"MY" }, { id:4, name: "om", city:"CH" }, { id:5, name: "ken", city:"JP" } ], obj = { "CA": "Canada", "MY": "Myanmmar", "IN": "India" }; const res = arrobj.map(({ city, ...e }) => ({ ...e, city: obj[city] || city })); console.log(res);
This might be the solution you are looking for
https://jsfiddle.net/sd7102v9/1/
var arrobj =[
{id:1, name: "xyz", city:"IN"},
{id:2, name: "abc", city:"CA"},
{id:3, name: "jon", city:"MY"},
{id:4, name: "om", city:"CH"},
{id:5, name: "ken", city:"JP"},
]
var obj=
{
"CA" : "Canada",
"MY" : "Myanmmar",
"IN" : "India"
}
var result = arrobj.map(e=>
{
let city = e.city;
if(typeof obj[city] !== 'undefined')
e.city = obj[city];
return e;
})
console.log(arrobj)
The following makes sure the original array remains unchanged and only those results are returned where the city name could be resolved:
const arrobj =[ {id:1, name: "xyz", city:"IN"}, {id:2, name: "abc", city:"CA"}, {id:3, name: "jon", city:"MY"}, {id:4, name: "om", city:"CH"}, {id:5, name: "ken", city:"JP"}], obj={"CA": "Canada","MY": "Myanmmar","IN": "India"}; res=arrobj.reduce((a,c)=>(obj[c.city] && a.push({...c,city:obj[c.city]}),a), []); console.log(res)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.