iT邦幫忙

0

請問JS如何把這個Array修改成Object

  • 分享至 

  • xImage

想請問如何把這個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" },
 };

froce iT邦大師 1 級 ‧ 2022-09-22 18:13:32 檢舉
可以轉換,但轉了有比較好處理嗎?科科
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
0
水無痕
iT邦新手 3 級 ‧ 2022-09-22 18:10:04
最佳解答
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);
cba246246 iT邦新手 4 級 ‧ 2022-09-25 19:48:04 檢舉

謝謝解答
有順利完成了

0
japhenchen
iT邦超人 1 級 ‧ 2022-09-23 07:55:38
Object.assign({}, ['a','b','c']); // {0:"a", 1:"b", 2:"c"}
cba246246 iT邦新手 4 級 ‧ 2022-09-25 19:48:17 檢舉

謝謝回答

0
tigernaxo
iT邦新手 5 級 ‧ 2022-09-23 11:30:45
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
	}})
,{})
cba246246 iT邦新手 4 級 ‧ 2022-09-25 19:48:22 檢舉

謝謝回答

我要發表回答

立即登入回答