js改变对象的key,把key替换成想要的key,值不变

js改变对象的key,把key替换成想要的key,值不变
例如把接口返回对象data {id:“11”,name:“张三”} 的key值替换成 {序列:“11”,姓名:“张三” }
data {id:‘11’,name:‘张三’}
var keyMap = {id: ‘序列’, name: ‘姓名’}
var objs= Object.keys(data).reduce((newData, key) => {
let newKey = keyMap[key] || key
newData[newKey] = data[key]
return newData
}, {})
alert(objs)
data对象就变成了 {序列:“11”,姓名:“张三” }
该方法可随意替换对象的key值,对对象属性数量、排序无要求

原文链接:https://blog.csdn.net/w19970824/article/details/88060209

var obj = {
"a":"nihoa", //和这样写法的区别
b:"wobuhoa", //注意这样的写法
"c":"lalala"
}
var arr = ['a',"b",3,4,5]
var zzz = arr[1];
console.log(zzz); //取到b
console.log(obj.zzz); //这样取到undefined
console.log(obj[zzz]) //正确取到wobuhoa
console.log(obj["a"]) //正确取到nihoa
console.log(obj.a) //正确取到nihoa
console.log("___________________________________________")
console.log(obj.a); //nihoa
console.log(obj.b); //wobuhoa
console.log(obj.c); //lalala
image.png
var obj ='{"a":"nihoa","b":"wobuhoa","c":"lalala"}'
console.log(JSON.parse(obj))

var json = {result:true, count:42};
console.log(JSON.stringify(json))
image.png

第一种形式 [[ ]]

[["12","32","56","10","67","89","12","12","8","42","33","9"]]

怎么处理上面的数据,处理以后是以下的形式;因为我要在页面上循环遍历

["12","32","56","10","67","89","12","12","8","42","33","9"]

解决方案 eval(数据)

eval(数据)可以对数据进行运算,例如返回数组对象,自动去掉外面多于的[]

  this.tableData=eval(e.data);

第二种形式 {"属性名":"属性值"}

{"sz":["12","32","56","10","67","89","12","12","8","42","33","9"]}

我要获取["12","32","56","10","67","89","12","12","8","42","33","9"]

解决方案

       var obj = eval('(' + e.data + ')');
            alert(obj.sz);
          this.tableData=obj.sz;

改变key

let arr=[{evaluateResult: "A类", evaluateTotal: 22},{evaluateResult: "B类", evaluateTotal: 22}]
      let keyMap = {evaluateResult: 'name', evaluateTotal: 'value'}
        arr.map(item=>{
          var objs= Object.keys(item).reduce((newData, key) => {
          let newKey = keyMap[key] || key
          newData[newKey] = item[key]
          return newData
          }, {})
         console.log(objs)
        })
## [JS数组reduce()方法](https://www.cnblogs.com/zhaofeis/p/10620226.html)

arr.reduce(function(prev,cur,index,arr){
...
}, init);

或者

arr.reduce(function(prev,cur,index,arr){
...
},);

**arr** 表示将要原数组;
**prev** 表示上一次调用回调时的返回值,或者初始值 init;
**cur** 表示当前正在处理的数组元素;
**index** 表示当前正在处理的数组元素的索引,若提供 init 值,则索引为0,否则索引为1;
**init** 表示初始值。

常用的参数只有两个:**prev** 和 **cur**。

数组求和,求乘积

var  arr = [1, 2, 3, 4];
var sum = arr.reduce((x,y)=>x+y)
var mul = arr.reduce((x,y)=>x*y)
console.log( sum ); //求和,10
console.log( mul ); //求乘积,24


计算数组中每个元素出现的次数

let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

let nameNum = names.reduce((pre,cur)=>{
  if(cur in pre){
    pre[cur]++
  }else{
    pre[cur] = 1 
  }
  return pre
},{})
console.log(nameNum); //{Alice: 2, Bob: 1, Tiff: 1, Bruce: 1}数组去重

let arr = [1,2,3,4,4,1]
let newArr = arr.reduce((pre,cur)=>{
    if(!pre.includes(cur)){
      return pre.concat(cur)
    }else{
      return pre
    }
},[])
console.log(newArr);// [1, 2, 3, 4]

let arr = [[0, 1], [2, 3], [4, 5]]
let newArr = arr.reduce((pre,cur)=>{
    return pre.concat(cur)
},[])
console.log(newArr); // [0, 1, 2, 3, 4, 5]

let arr = [[0, 1], [2, 3], [4,[5,6,7]]]
const newArr = function(arr){
   return arr.reduce((pre,cur)=>pre.concat(Array.isArray(cur)?newArr(cur):cur),[])
}
console.log(newArr(arr)); //[0, 1, 2, 3, 4, 5, 6, 7]

var result = [
    {
        subject: 'math',
        score: 10
    },
    {
        subject: 'chinese',
        score: 20
    },
    {
        subject: 'english',
        score: 30
    }
];

var sum = result.reduce(function(prev, cur) {
    return cur.score + prev;
}, 0);
console.log(sum) //60

改变对象key的位置

var data = {
            first: {
                'name': 'zhangsan',
                'id': 99,
                'sex': 'nan',
                'age': 19,
                
            },
            second: {
                'name': '李四',
                'sex': '女',
                'id': 108,
                'age': 25
            }
        }
        var obj = {};
        for(var i in data) {
            obj = {
                "id": data[i]['id'],
                "name": data[i]['name'],
                "age": data[i]['age'],
                'sex': data[i]['sex']
            }
            data[i] = obj;
        }
        console.log(data);

你可能感兴趣的:(js改变对象的key,把key替换成想要的key,值不变)