我想编写一个以对象数组作为参数的函数。如果数组中的对象包含键" name,"我想将该密钥更改为" title。"然后我想返回更改了所有键的对象数组的更新版本。
这是我尝试这样做的。它没有按照我的意愿行事。
execute

以上代码返回:
const people = [{age: 32},{name: 'bob'},{name: 'jack', age: 3}];
function nameToTitle(arr){
let result = [];
for(let i = 0; i < arr.length; i++){
if(arr[i].name){
let newObj = {};
for(let x in arr[i]){
if(arr[i][x] === 'name'){
newObj['title'] = arr[i][x];
}
else {
newObj[x] = arr[i][x];
}
}
result.push(newObj);
}
else {
result.push(arr[i])
}
}
return result;
}
console.log(nameToTitle(people));
它不会将名称密钥更改为&#34; title。&#34;
答案 0 :(得分:3)
以下代码适用于您的用例。请注意,我已将people
更改为可变变量(不再是const
)。基本上所有这一切都是遍历数组中的每个字典,如果它找到一个带有"name"
键的字典,它会设置一个具有相同值的"title"
键,然后删除"name"
键。
var people = [{age: 32}, {name: 'bob'}, {name: 'jack', age: 3}];
for (var i = 0; i < people.length; i++) {
if (people[i].hasOwnProperty("name")) {
people[i]["title"] = people[i]["name"];
delete people[i]["name"];
}
}
console.log(people);
答案 1 :(得分:3)
你非常接近,你的if条件是检查对象的值而不是密钥。所以你需要做的就是改变:
if(arr[i][x] === 'name') // 'bob' === 'name' for {name: 'bob'}
为:
if(x === 'name') // 'name' === 'name' for {name: 'bob'}
因为x
中for(let x in arr[i])
的值是您要迭代的键值。
const people = [{age: 32},{name: 'bob'},{name: 'jack', age: 3}];
function nameToTitle(arr){
let result = [];
for(let i = 0; i < arr.length; i++){
if(arr[i].name){
let newObj = {};
for(let x in arr[i]){
if(x === 'name'){
newObj['title'] = arr[i][x];
}
else {
newObj[x] = arr[i][x];
}
}
result.push(newObj);
}
else {
result.push(arr[i])
}
}
return result;
}
console.log(nameToTitle(people));
&#13;
答案 2 :(得分:1)
const people = [{age: 32},{name: 'bob'},{name: 'jack', age: 3}];
// Copy all properties. If key is 'name' change it to 'title'
const copyObjectWithTitle = obj =>
Object.keys(obj).reduce((objAcc, key) => {
const value = obj[key];
return Object.assign({}, objAcc, key === 'name' ? { title: value} : { [key]: value });
}, {})
// Map over the list. If the object has the key 'name' return a copy with the key 'title'
const nameToTitle = (list) => list.map(obj => obj.hasOwnProperty('name') ? copyObjectWithTitle(obj) : Object.assign({}, obj))
const updatedPeople = nameToTitle(people);
答案 3 :(得分:1)
您可以映射数组中的对象并修改具有name属性的对象,如下所示
peoples.map(people => {
if(people.hasOwnProperty('name')) {
let title = people.name;
delete people.name;
return Object.assign({}, people, {title: title});
}
return people;
})
答案 4 :(得分:0)
如果您只想将name
属性更改为title
,我会这样做:
function nameToTitle(objsArray){
var s = objsArray.slice(), a; // make a copy
for(var i in s){
a = s[i];
if(a.name){
s[i].title = a.name; delete s[i].name;
}
}
return s;
}
var objsArray = [{age:32},{name:'bob'},{name:'jack', age:3}];
console.log(nameToTitle(objsArray));
&#13;
答案 5 :(得分:-1)
这可能会有所下降,但只是为了好玩:]
const people = [{age: 32}, {name: 'bob'}, {name: 'jack', age: 3}];
const result = eval(JSON.stringify(people).replace(/\bname\b/g, 'title'));
console.log(result);