简体   繁体   English

如何遍历嵌套对象并组合键和值?

[英]How to iterate through nested Objects and combine key and value?

const products = {
  value: {
    phone: [],
    lamp: [],
    car: ["bmw", "toyota", "audi"]
  }
};

In the given object I want to iterate and get keys .在给定的 object 中,我想迭代并获取keys
Note that values are array of strings .请注意, valuesarray of strings

I'd like to get all keys and if values are not empty arrays I want to combine with keys and return an array with this structure我想获取所有键,如果值不为空 arrays 我想与键结合并返回具有此结构的数组

   [
    phone,
    lamp,
    car-bmw,
    car-toyota,
    car-audi
  ]

Here is what I did so far, which is not what I want这是我到目前为止所做的,这不是我想要的

 const products = { value: { phone: [], lamp: [], car: ["bmw", "toyota", "audi"] } }; const mappedProducts = Object.entries(products.value).map(([value, items]) => { //console.log("value:", value, "items:", items) if (items.length > 0) { return { car: items.map((c) => c) }; } }); console.log(mappedProducts);

Any help will be appreciated.任何帮助将不胜感激。

I modified what you did a bit, you can you flatMap我修改了你所做的一点,你可以flatMap

 const products = { value: { phone: [], lamp: [], car: ["bmw", "toyota", "audi"] } }; const mappedProducts = Object.entries(products.value).flatMap(([value, items]) => { //console.log("value:", value, "items:", items) if (items.length > 0) { return items.map(item => `${value}-${item}`); } else { return [value]; } }); console.log(mappedProducts);

You can use for in loop你可以for in循环中使用

 const products = { value: { phone: [], lamp: [], car: ["bmw", "toyota", "audi"] } }; const newData = []; for (const key in products) { const value = products[key]; for (const innerKey in value) { const innerVal = value[innerKey]; if (innerVal.length > 0) { innerVal.forEach((item) => newData.push(`${innerKey}-${item}`)); } else { newData.push(innerKey); } } } console.log(newData);

Another solution would be to use Object.keys() along with map and concat to get a merged array with keys and values (if any):另一种解决方案是使用Object.keys()以及mapconcat来获取包含键和值(如果有)的合并数组:

const products = {
  value: {
    phone: [],
    lamp: [],
    car: ["bmw", "toyota", "audi"]
  }
};

let keys = [].concat.apply([], Object.keys(products.value).map((key) =>{
    if(products.value[key].length > 0){
    return products.value[key];
  }
  else return key;
}));
console.log(keys);

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

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