[英]how do you convert javascript object with arrays in to array of objects with corresponding name and value?
Fellow programmer here, for some reason I have spent two days but I cannot do this properly so help me out.这里的程序员同事,由于某种原因,我花了两天时间,但我不能正确地做到这一点,所以请帮帮我。 I have an object with arrays for each key like this:
对于每个键,我有一个 object 和 arrays,如下所示:
var arraysObject = { "North American": [ "CONUS", "NAMER", "CONUS/AK", "US-NC", "US-NE", "US-NW", "US-SC", "US-SE" ], "Oconus": [ "ALASKA", "GUAM", "HAWAII", "POLAR", "US-SAMOA" ], }
I have a list of areas that have been selected, like the following我有一个已选择的区域列表,如下所示
var listOfAreas = ["CONUS", "GUAM","US-SAMOA"]
I want to create the following object:我想创建以下 object:
var result = [{ "North American":"CONUS", "Oconus": "GUAM" }, { "North American": "", "Oconus":"US-SAMOA" }]
Notice how it created a new object only when that last one's key is full and fills the object if possible.请注意,仅当最后一个密钥已满并尽可能填充 object 时,它才会创建新的 object。 in my implementation it creates an object for each individual string and assigns it to the key using then pushes it using.map This doesn't work.
在我的实现中,它为每个单独的字符串创建一个 object 并将其分配给密钥 using 然后使用它推送它。map 这不起作用。 I want it to fill each object accordingly and create an new object only when it is necessary.
我希望它相应地填充每个 object 并仅在必要时创建一个新的 object。 Appreciate your help.
感谢你的帮助。 Best, A dummy.
最好的,一个假人。
You could take an object for keeping track of the indices for the keys and take a helper object for the reverted value/key relation.您可以使用 object 来跟踪键的索引,并使用帮助器 object 来还原值/键关系。
const arraysObject = { "North American": ["CONUS", "NAMER", "CONUS/AK", "US-NC", "US-NE", "US-NW", "US-SC", "US-SE"], "Oconus": ["ALASKA", "GUAM", "HAWAII", "POLAR", "US-SAMOA"] }, keys = Object.fromEntries(Object.entries(arraysObject).flatMap(([k, a]) => a.map(v => [v, k]))), EMPTY = Object.fromEntries(Object.keys(arraysObject).map(k => [k, ''])), listOfAreas = ["CONUS", "GUAM","US-SAMOA"], indices = {}, result = []; listOfAreas.forEach(value => { const key = keys[value]; indices[key]??= 0; (result[indices[key]++]??= {...EMPTY })[key] = value; }); console.log(result);
.as-console-wrapper { max-height: 100%;important: top; 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.