如何编写方法,该方法在输出时会将具有字符“ _”的键转换为空格。同时,我们不能绑定快捷键,而要使该方法具有通用性,它将自身进行查找和转换。
const arr = [{
"name": "BMW",
"price": "55 000",
"color": "red",
"constructor_man": "Billy%Zekun" //should become "constructor man"
}, {
"name": "MERSEDEC",
"price": "63 000",
"color": "blue",
"constructor_man": "Jon%Adams" //should become "constructor man"
}, {
"name_car": "Lada", //should become "name car"
"price": "93 000",
"color": "blue",
"constructor_man": "Bar John", //should become "constructor man"
"door": "3"
}, {
"name": "TOYOTA",
"price": "48 000",
"color": "blue",
"constructor_man": "Jon Hubert", //should become "constructor man"
"door": "3",
"max_people": "7" //should become "max people"
}
];
答案 0 :(得分:0)
您使用for...of
在数组中循环。然后使用for...in
遍历每个对象。如果键为includes _
,请替换为' '
。用_
delete键:
const arr = [{"name":"BMW","price":"55 000","color":"red","constructor_man":"Billy%Zekun"},{"name":"MERSEDEC","price":"63 000","color":"blue","constructor_man":"Jon%Adams"},{"name_car":"Lada","price":"93 000","color":"blue","constructor_man":"Bar John","door":"3"},{"name":"TOYOTA","price":"48 000","color":"blue","constructor_man":"Jon Hubert","door":"3","max_people":"7"}];
for (let item of arr) {
for (let key in item) {
if (key.includes('_')) {
item[key.replace(/_/g, ' ')] = item[key];
delete item[key]
}
}
}
console.log(arr)
答案 1 :(得分:0)
您可以使用以下方法:
const arr = [{
"name": "BMW",
"price": "55 000",
"color": "red",
"constructor_man": "Billy%Zekun" //should become "constructor man"
}, {
"name": "MERSEDEC",
"price": "63 000",
"color": "blue",
"constructor_man": "Jon%Adams" //should become "constructor man"
}, {
"name_car": "Lada", //should become "name car"
"price": "93 000",
"color": "blue",
"constructor_man": "Bar John", //should become "constructor man"
"door": "3"
}, {
"name": "TOYOTA",
"price": "48 000",
"color": "blue",
"constructor_man": "Jon Hubert", //should become "constructor man"
"door": "3",
"max_people": "7" //should become "max people"
}
];
const underscoreReplacer = src => src.map(item => Object.entries(item).reduce((obj,keyValue) => {obj[keyValue[0].replace('_',' ')]=keyValue[1];return obj},{}));
console.log(underscoreReplacer(arr));
.as-console-wrapper {
max-height:100% !important;
top: 0;
}
答案 2 :(得分:0)
var underScoreReplacer = function(myArray){
var temp = [];
myArray.forEach(object => {
var tempObj = {};
Object.keys(object).forEach(key => {
tempObj[key.replace("_", "#")] = object[key];
});
temp.push(tempObj);
});
return temp;
}
var myArray = [
{
name:"BMW",
price:"55 000",
color:"red",
constructor_man:"Billy%Zekun" //should become "constructor man"
}
];
myArray = underScoreReplacer(myArray);
console.log(myArray);