我需要將具有鍵值的物件轉換為包含新 const 命名表單平臺的新物件,并且在 js 中具有名稱到值怎么做?
posters: [
{ platform: facebook; name: ["user test1","user test2"] },
{ platform: instagram; name: ["Ig test1","Ig test2"] },
]
進入
posters: {
facebook: ["user test1","user test2"] ,
instagram: ["Ig test1","Ig test2"] ,
}
uj5u.com熱心網友回復:
您的輸入陣列無效。您的平臺值周圍沒有字串,并且您使用分號而不是逗號分隔物件屬性。所以你需要解決這個問題才能繼續。
看起來好像
posters是更大物件中的一個屬性,所以這個答案將考慮到這一點。
在海報陣列上使用reduce以迭代陣列中的物件并回傳一個物件,其中鍵是平臺名稱,值是name陣列。
由于它看起來像是posters在一個更大的物件中,我們將使用擴展語法重建物件。
const data={posters:[{platform:"facebook",name:["user test1","user test2"]},{platform:"instagram",name:["Ig test1","Ig test2"]}]};
// Create a new object
const updated = {
// Spread out the old object into it
...data,
// And replace the old `posters` property with an
// object using `reduce`. Destructure the `platform`
// and `name` properties from the object, and then
// use them to add a key and a value to the initial
// object (`acc`/accumulator)
posters: data.posters.reduce((acc, obj) => {
const { platform, name } = obj;
acc[platform] = name;
return acc;
}, {})
};
console.log(updated);
附加檔案
- 解構賦值
uj5u.com熱心網友回復:
const postersArray = [
{ platform: facebook, name: ["user test1","user test2"] },
{ platform: instagram, name: ["Ig test1","Ig test2"] }
]
const postersObject = postersArray.reduce((previous, current) => {
return {
…previous,
[current.platform]: current.name
}
},{})
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/512806.html
上一篇:更改具有條件的物件陣列中的所有值
