JavaScript中将对象数组中的某个属性值,批量替换成另一个数值

原文链接

https://segmentfault.com/q/1010000010352622

希望将下列数组中的sh替换成沪,sz替换成深

var stooges = [
            {label:1,value:1,placeCode: 'sh', stock_code: 40},
            {label:1,value:1,placeCode: 'sh', stock_code: 50},
            {label:1,value:1,placeCode: 'sz', stock_code: 60,status:1},
            {label:1,value:1,placeCode: 'sz', stock_code: 39,status:1}
        ];
我能想到的:
 1 var stooges = [
 2   {label: 1, value: 1, placeCode: 'sh', stock_code: 40},
 3   {label: 1, value: 1, placeCode: 'sh', stock_code: 50},
 4   {label: 1, value: 1, placeCode: 'sz', stock_code: 60, status: 1},
 5   {label: 1, value: 1, placeCode: 'sz', stock_code: 39, status: 1}
 6 ];
 7 
 8 for (var i = 0; i < stooges.length; i++) {
 9   var item = stooges[i];
10   if (item.placeCode == "sh") {
11     item.placeCode = "沪";
12   }
13   if (item.placeCode == "sz") {
14     item.placeCode = "深";
15   }
16 }
17 写个for循环遍历一下,从第一个对象开始,发现对应的placeCode是sh则更新成文字沪,发现对应的placeCode是sz则更新成文字深,一直到最后一个对象

 

最简便:

1 for(var i=0;i){
2     stooges[i].placeCode === 'sh'?stooges[i].placeCode = '沪': stooges[i].placeCode = '深'
3 }

 


第二种
var maps= new Map([['sh','沪'],['sz','深圳']]);
stooges = stooges.map(element =>{
    element.placeCode = maps.get(element.placeCode);
    return element;
});

  

第三种

var toStr = {
    sh : '沪',
    sz : '深'    
};
stooges.map(function(value){
    var placeCode = value.placeCode;
    value.placeCode = toStr[placeCode] ? toStr[placeCode] : placeCode;
    return value;
}); 

  

再次定义一个对象,

定义一个返回vlaue的函数;

map一下

转载于:https://www.cnblogs.com/qianjinyan/p/8891820.html

你可能感兴趣的:(JavaScript中将对象数组中的某个属性值,批量替换成另一个数值)