比如我要把
[
{'mingzi':'zhangsan','nianling':24},
{'mingzi':'lisi','nianling':25}
]
,这样一个数组对象的键名替换,最后生成
[
{'name':'zhangsan','age':24},
{'name':'lisi','age':25}
]
应该如何做呢?
比如我要把
[
{'mingzi':'zhangsan','nianling':24},
{'mingzi':'lisi','nianling':25}
]
,这样一个数组对象的键名替换,最后生成
[
{'name':'zhangsan','age':24},
{'name':'lisi','age':25}
]
应该如何做呢?
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);
10 回答11.3k 阅读
5 回答4.9k 阅读✓ 已解决
4 回答3.2k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答5.2k 阅读✓ 已解决
2 回答4.8k 阅读✓ 已解决
4 回答4.4k 阅读✓ 已解决