[英]Array Split Inside Objects
I have an object Regions{}
which stores multiple objects, following code block showing countryName : [regions,..,..]
我有一个对象
Regions{}
,它存储多个对象,下面的代码块显示countryName : [regions,..,..]
Regions = { Afghanistan:["Badakhshan~BDS", "Badghis~BDG", "Baghlan~BGL"]
Albania:["Berat~01", "Dibër~09", "Durrës~02",]
}
Which giving me result like this: 这给了我这样的结果:
Afghanistan: Array(n)
0: "Badakhshan~BDS"
1: "Badghis~BDG"
what I am trying to achive is : 我想要达到的是:
Afghanistan: Array(n)
0:{value: "Badakhshan", lable: "BDS"}
1:{value: "Badghis", lable: "BDG"}
thanks in advance 提前致谢
PS: for the sake of some ruthless fellows following is the code what I have tried yet 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
}
})
You can use split
and map
, this code is changing values in original object, if you want to build a new object you can use reduce
instead of forEach
您可以使用
split
和map
,此代码正在更改原始对象中的值,如果要构建新对象,可以使用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)
Do something like: 做类似的事情:
Regions.map(region => region.map(txt => {
const [val, lbl] = txt.split("~");
return { value: val, lable: lbl};
}));
Messy but gets the work done. 凌乱,但完成工作。 Using nested
forEach
loops 使用嵌套的
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)
Use the map function to iterate the object. 使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.