zoukankan      html  css  js  c++  java
  • 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<stooges.length;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一下

  • 相关阅读:
    团队-爬取豆瓣电影TOP250-成员简介及分工
    结对-贪吃蛇游戏-需求分析
    个人编程作业
    团队项目编程作业
    课后作业-阅读任务-阅读提问-1
    团队-爬虫豆瓣电影TOP250-成员简介及分工
    结对-英文词频检测程序-需求分析
    对软件工程课程的期望
    自我介绍
    作业0
  • 原文地址:https://www.cnblogs.com/qianjinyan/p/8891820.html
Copyright © 2011-2022 走看看