所以我的任务是创建一个函数,该函数获取第一个值并使其成为我的新obj中的新键和第二个值并将其保留为键仍然我知道我必须遍历数组并引用每个使用点表示法的值,但是当我尝试将值赋值为键时,它给了我一个错误,我知道它因为它被评估为字符串但是必须有一些更简单的方法,这里是代码
var people = [ {name: "Anthony", score: 10},
{name: "Fred", score : 10},
{name: "Anthony", score: -8},
{name: "Winnie", score: 12}];
function countScores(people) {
var obj = people[0]
var key = obj.name
var value = obj.score
}
countScores(people)
答案 0 :(得分:0)
var people = [
{name: "Anthony", score: 10},
{name: "Fred", score: 10},
{name: "Anthony", score: -8},
{name: "Winnie", score: 12}
];
function countScores(people) {
var target = {};
for (var i=0; i<people.length; i++) {
var obj = people[i];
target[obj.name] = obj.score;
}
return target;
}
console.log(countScores(people));