[英]converting an array into an object javascript
output: Array(5) [ "Samsung", "Iphone", "Nokia", "Xiomi", "Blackberry" ]
another output:
Array(5) [ Object { id: "Samsung", label: "Samsung" },Object { id: "Iphone", label: "Iphone"},
Object { id: "Nokia", label: "Nokia"},Object { id: "Xiomi", label: "Xiomi"},Object { id: "Blackberry", label: "Blackberry"} ]
我希望我的第一個 output 轉換為第二個 output 的類型。 我正在嘗試這樣做:
mobilePhones = [
{
label: Object.keys(this.state.details.phones),
id: Object.keys(this.state.details.phones,
}
]
但得到空的手機。 我的 state 的類型是:
state = {
details:{
phones: {},
}
}
我正在將手機 object 轉換為數組,以便我可以在 const mobilePhones 上對其進行迭代,然后再次希望它轉換為 object 類型。它讓我感到困惑。 誰能幫我解決這個問題。
const output = [ "Samsung", "Iphone", "Nokia", "Xiomi", "Blackberry" ] const brands = output.map(brand => ({id: brand, label: brand})); console.log(brands);
為此使用array.map
。
let array = [ "Samsung", "Iphone", "Nokia", "Xiomi", "Blackberry" ] let result = array.map( el => { return {id: el, label: el}}) console.log(result);
您可以使用 map function 來獲得第二個數組的結果。
const type2 = type1.map((item) => {
return {
id: item,
label: item
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.