[英]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.