本文介绍了使用lodash重新映射属性名称和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个数组:
aItems = [{
"PropertyA": "apple",
"PropertyB": "banana",
"PropertyC": "dog",
"PropertyD": "hotdog",
"PropertyE": "coldcat",
"PropertyF": "Y",
"PropertyG": "N"
},
...,
{
"PropertyA": "this",
"PropertyB": "is",
"PropertyC": "json",
"PropertyD": "code",
"PropertyE": "wow",
"PropertyF": "N",
"PropertyG": "N"
}]
我想用 lodash 来获得这个结果:
I would like use lodash to obtain this result:
aItems = [{
"propertyA": "apple",
"propertyB": "banana",
"propertyC": "dog",
"propertyD": "hotdog",
"propertyE": "coldcat",
"propertyNEW": true,
"propertyG": false
},
...,
{
"propertyA": "this",
"propertyB": "is",
"propertyC": "json",
"propertyD": "code",
"propertyE": "wow",
"propertyNEW": false,
"propertyG": false
}]
我想用其他名称映射每个属性名称,并更改某些特定属性的值。
我可以使用 lodash 吗?
I want map each property name with other names and change the value for some specific properties.Can I do it using lodash?
推荐答案
创建新旧映射密钥,像这样
Create a mapping of old and new keys, like this
var keyMapping = {'PropertyA': 'propertyA', ..., 'PropertyF': 'propertyNEW'}
以及旧值和新值的映射,例如
and also a mapping of old and new values, like this
var valueMapping = {'Y': true, 'F': false}
然后使用和,你可以变换对象,就像这样
And then using _.map
and _.transform
, you can transform the object, like this
var result = _.map(allItems, function(currentObject) {
return _.transform(currentObject, function(result, value, key) {
if (key === 'PropertyF' || key === 'PropertyG') {
value = valueMapping(value);
}
result[keyMapping[key]] = value;
});
});
这篇关于使用lodash重新映射属性名称和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!