想請問如何把這個array修改成下面那個object
小弟本來想用forEach然後把name的value放到object裡當key使用
但是好像沒辦法
const personArray = [
{ name: "Kyle", age: 25, female: "man" },
{ name: "Helen", age: 18, female: "woman" },
{ name: "Ray", age: 33, female: "man" },
];
修改成
const personObh = {
Kyle: { age: 25, female: "man" },
Helen: { age: 18, female: "woman" },
Ray: { age: 33, female: "man" },
};
const personArray = [
{ name: "Kyle", age: 25, female: "man" },
{ name: "Helen", age: 18, female: "woman" },
{ name: "Ray", age: 33, female: "man" },
];
const resultObject = {};
for(let person of personArray) {
resultObject[person.name] = person;
}
console.log(resultObject);
const personArray = [
{ name: "Kyle", age: 25, female: "man" },
{ name: "Helen", age: 18, female: "woman" },
{ name: "Ray", age: 33, female: "man" },
];
const resultObject = personArray.reduce((obj,person) => {
obj[person.name] = person;
return obj;
}, {})
console.log(resultObject);
Object.assign({}, ['a','b','c']); // {0:"a", 1:"b", 2:"c"}
const personArray = [
{ name: "Kyle", age: 25, female: "man" },
{ name: "Helen", age: 18, female: "woman" },
{ name: "Ray", age: 33, female: "man" },
];
const personObh = personArray.reduce((obj, p)=>
Object.assign(obj, {
[p.name]: {
age: p.age,
female:p.female
}})
,{})