嵌套地图功能| Node.js

时间:2019-12-05 06:35:29

标签: javascript node.js nested maps

我需要将类别和子类别存储在Node.js中的地图中,以下代码似乎无效,请告知我在这里做错了什么。 (PS-我对Node.js和Java语言很陌生)

var list = [
    {name:'orange', category: "fruit", sub: 'citrus', price: 1.22 },
    {name:'pineapple', category: "fruit", sub: 'tropical', price: 2.22 },
    {name:'coke', category: "drink", sub: 'cola', price: 3.33 },
    {name:'beer', category: "drink", sub: 'alcohol', price: .44 },
]; 
function dictionary(list) {
    var map = {};
    for (var i = 0; i < list.length; ++i) {
        var category = list[i].category;
        var sub = list[i].sub;
        if (!map[category]) 
            map[category] = {};
            if (!map[category][sub])
                map[categpry][sub]=[];
            map[category][sub].push(list[i].name);
        // map[category].push(list[i]);
    }
    return map; }

2 个答案:

答案 0 :(得分:0)

dictionary函数将为您提供一系列子类别作为地图。

var list = [
    {name:'orange', category: "fruit", sub: 'citrus', price: 1.22 },
    {name:'pineapple', category: "fruit", sub: 'tropical', price: 2.22 },
    {name:'coke', category: "drink", sub: 'cola', price: 3.33 },
    {name:'beer', category: "drink", sub: 'alcohol', price: .44 },
]; 

function dictionary(list) {
    var map = {};

    list.forEach(item => {
      if (!Array.isArray(map[item.category])) {
        map[item.category] = [item.sub];
      } else {
        map[item.category].push(item.sub);
      }
    });

    return map;
}

示例输出:

{
  drink: ["cola", "alcohol"],
  fruit: ["citrus", "tropical"]
}

答案 1 :(得分:0)

希望这会对您有所帮助:)

const list = [
  { name: "orange", category: "fruit", sub: "citrus", price: 1.22 },
  { name: "pineapple", category: "fruit", sub: "tropical", price: 2.22 },
  { name: "coke", category: "drink", sub: "cola", price: 3.33 },
  { name: "beer", category: "drink", sub: "alcohol", price: 0.44 }
];
function dictionary(list) {
  const map = {};
  for (let item of list) {
    !map[item.category] && (map[item.category] = []);
    map[item.category].push(item.sub);
  }
  console.log(map);
  return map;
}

dictionary(list);