Home > Enterprise >  replace an object in an array without convert array to string javascript app script
replace an object in an array without convert array to string javascript app script

Time:04-27

I'm using app script to get information from API and use it as JSON.

var data = UrlFetchApp.fetch(***);
var obj = JSON.parse(data); // To JSON
Logger.log(typeof(obj)); // return type as object

example of return array JSON:

var dataJson = [{age=20, gender=female, country=usa, name=sali, type=female},{age=25, gender=male, country=usa, name=john, type=female},{age=19, gender=female, country=usa, name=anita, type=female},{age=22, gender=male, country=usa, name=fredo, type=female}]

I want if gender = female change country to uk. and if gender = male change country to canada.

I want after update array keep type as object not as string.

result as:

[{age=20, gender=female, country=uk, name=sali, type=female},{age=25, gender=male, country=canada, name=john, type=female},{age=19, gender=female, country=uk, name=anita, type=female},{age=22, gender=male, country=canada, name=fredo, type=female}]

note: the data in not fixed is changed dynamic.

CodePudding user response:

Are you simply looking for:

dataJson = dataJson.map(elem => {
    if(elem.gender === 'female'){
        elem.country = 'uk'
    }
    if(elem.gender === 'male'){
        elem.country = 'canada'
    }
    return elem
})

CodePudding user response:

You can simply map over it

var dataJson = [{age:20, gender:'female', country:'usa', name:'sali', type:'female'},{age:25, gender:'male', country:'usa', name:'john', type:'male'}]


const result = dataJson.map(({gender, ...rest}) => {
const isFemale = gender === 'female'
 return {
   ...rest,
   gender: isFemale? 'woman': 'man',
   country: isFemale ?'uk': 'canada'
 }
})

console.log(result)

  • Related