请问vue如何替换数组对象的键名呢?

比如我要把

[
    {'mingzi':'zhangsan','nianling':24},
    {'mingzi':'lisi','nianling':25}
]

,这样一个数组对象的键名替换,最后生成

[
    {'name':'zhangsan','age':24},
    {'name':'lisi','age':25}
]

应该如何做呢?

阅读 6.9k
4 个回答
let data = [{
    'mingzi': 'zhangsan',
    'nianling': 24
  },
  {
    'mingzi': 'lisi',
    'nianling': 25
  }
]
let result = data.map(item => ({
  name: item.mingzi,
  age: item.nianling
}));
console.log(result);
let arr = [
    {'mingzi':'zhangsan','nianling':24},
    {'mingzi':'lisi','nianling':25}
];
let newArr = JSON.parse(JSON.stringify(arr).replace(/mingzi/g, "name").replace(/nianling/g, "age"));
console.log(newArr);

新建一个匹配对象

let matchObj = {
'mingzi': 'name',
'nianling: 'age'
}
let data = [{
    'mingzi': 'zhangsan',
    'nianling': 24
  },
  {
    'mingzi': 'lisi',
    'nianling': 25
  }
]
let result = data.map(item => ({
  [matchObj.mingzi]: item.mingzi,
  [matchObj.nianling]: item.nianling
}));
console.log(result);

跟上面的差不多

let matchObj = {
  'mingzi': 'name',
  'nianling': 'age'
}
let data = [{
    'mingzi': 'zhangsan',
    'nianling': 24
  },
  {
    'mingzi': 'lisi',
    'nianling': 25
  }
]
let result = data.map(item => {
    let data = {};
    Object.entries(item).forEach(([k, v]) => {
      data[matchObj[k] || k] = v;
    });
    return data;
});
console.log(result);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题