数组在对象内部拆分

时间:2019-08-07 09:27:23

标签: javascript arrays reactjs object

我有一个对象Regions{},其中存储了多个对象,下面的代码块显示了countryName : [regions,..,..]

Regions = { Afghanistan:["Badakhshan~BDS", "Badghis~BDG", "Baghlan~BGL"]
            Albania:["Berat~01", "Dibër~09", "Durrës~02",]
          }

给我这样的结果:

Afghanistan: Array(n)
0: "Badakhshan~BDS"
1: "Badghis~BDG"

我要达到的目标是:

Afghanistan: Array(n)    
0:{value: "Badakhshan", lable: "BDS"}
1:{value: "Badghis", lable: "BDG"}

预先感谢

PS:为了帮助一些无情的家伙,下面是我尝试过的代码

   let countries = CountryRegionData
      let regions = {}
      countries = countries.map(country => {
        regions = {
          ...regions,
          [country[0]]: country[2].split('|')
        }
        return {
          value: country[1],
          label: country[0]
        }
      })

      console.log("countries",countries)
      console.log("regions",regions)

     let values = regions["Afghanistan"]; 
     values = values.map(value =>{
       return {
         value: value,
         lable: value
       }
     })

4 个答案:

答案 0 :(得分:2)

您可以使用splitmap,此代码正在更改原始对象中的值,如果要构建新对象,可以使用reduce而不是forEach

let Regions = {
  Afghanistan: ["Badakhshan~BDS", "Badghis~BDG", "Baghlan~BGL"],
  Albania: ["Berat~01", "Dibër~09", "Durrës~02", ]
}

Object.entries(Regions).forEach(([key,value])=>{
  Regions[key] = value.map(data=>{
    let [value,label] = data.split('~')
    return {value,label}
  })
})

console.log(Regions)

答案 1 :(得分:1)

执行以下操作:

/^([A-Za-z0-9_\-\.]{1,64})+\@([A-Za-z0-9_\-\.]{1,253})+\.([A-Za-z]{2,4})$/

答案 2 :(得分:1)

混乱,但可以完成工作。使用嵌套的forEach循环

var Regions = {
  Afghanistan: ["Badakhshan~BDS", "Badghis~BDG", "Baghlan~BGL"],
  Albania: ["Berat~01", "Dibër~09", "Durrës~02", ]
}
var ar = [];
Object.keys(Regions).forEach(function(e) {
  Regions[e].forEach(function(k) {
    var arr = k.split('~');
    ar.push({
      value: arr[0],
      label: arr[1]
    })
  })
  Regions[e] = ar;
  ar = [];
})
console.log(Regions)

答案 3 :(得分:1)

使用map函数迭代对象。

Regions = {
  Afghanistan: ["Badakhshan~BDS", "Badghis~BDG", "Baghlan~BGL"],
  Albania: ["Berat~01", "Dibër~09", "Durrës~02", ]
};

const finalObject = Object.keys(Regions).map(region => {
  return {
    [region]: Regions[region].map(country => {
      const [value, lable] = country.split("~");
      return {
        value,
        lable
      };
    })
  };
});

console.log(finalObject);