简体   繁体   English

将数组转换为 object javascript

[英]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"} ]

I want my 1st output to get converted into the type of 2nd output.我希望我的第一个 output 转换为第二个 output 的类型。 I am trying to do this:我正在尝试这样做:

 mobilePhones = [
           {
           label: Object.keys(this.state.details.phones),
           id: Object.keys(this.state.details.phones,
           } 
         ]

but getting empty mobilePhones.但得到空的手机。 my state is of type:我的 state 的类型是:

  state = {
        details:{
          phones: {},
        }
      } 

I am converting phones object into array so that I can iterate it over const mobilePhones and then again want it to convert to the object type.Its getting confusing for me.我正在将手机 object 转换为数组,以便我可以在 const mobilePhones 上对其进行迭代,然后再次希望它转换为 object 类型。它让我感到困惑。 Can anyone please help me with this.谁能帮我解决这个问题。

 const output = [ "Samsung", "Iphone", "Nokia", "Xiomi", "Blackberry" ] const brands = output.map(brand => ({id: brand, label: brand})); console.log(brands);

Use array.map for this.为此使用array.map

 let array = [ "Samsung", "Iphone", "Nokia", "Xiomi", "Blackberry" ] let result = array.map( el => { return {id: el, label: el}}) console.log(result);

You can use map function to get the result of second array.您可以使用 map function 来获得第二个数组的结果。

const type2 = type1.map((item) => {
  return {
    id: item,
    label: item
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM