Javascript嵌套对象-创建访问嵌套对象的函数

时间:2018-08-19 23:47:10

标签: javascript object nested

下面的编码问题需要帮助。我被困住了,不胜感激!

--------------------------问题嵌套对象------------------ ---------

  

编写一个函数pumpkinPicker,给定一个深度嵌套的对象,该函数返回存储为值的“南瓜”字符串数的计数   在任何嵌套对象中。

var pumpkinPatch = {
  meadow: {
    byTheRock: 'apples',
    byThePuddle: 'pumpkin'
  },
  hill: {
    byTheBench: {
      leftOfBench: 'pumpkin',
      rightOfBench: 'pumpkin'
      },
      topOfHill: 'apples'
      }
    };


pumpkinPicker(pumpkinPatch); //*answer should prompt => 3*

3 个答案:

答案 0 :(得分:0)

我尚未对其进行测试,但这可能有助于您设定正确的方向:

function countValuesFromObject(object, value) {
    var count = 0;
    for (var prop in object) {
        var val = object[prop];
        if (val === value) {
            count++;
        }
        if (typeof val === 'object') {
            count += countValuesFromObject(val, value);
        }
    }
    return count;
}

答案 1 :(得分:0)

您可以递归地执行此操作,并使用for ... in循环,如下所示:

const pumpkinPicker = patch => {
  total = 0;
  
  for (const k in patch) {
    if (typeof patch[k] === "object") {
      total += pumpkinPicker(patch[k]);
    }
    else if (patch[k] === "pumpkin") {
      total++;
    }
  }
  
  return total;
};

var pumpkinPatch = {
  meadow: {
    byTheRock: 'apples',
    byThePuddle: 'pumpkin'
  },
  hill: {
    byTheBench: {
      leftOfBench: 'pumpkin',
      rightOfBench: 'pumpkin'
    },
    topOfHill: 'apples'
  }
};


console.log(pumpkinPicker(pumpkinPatch));

答案 2 :(得分:0)

递归函数中的

reduce()使这一点很简洁:

var pumpkinPatch = {meadow: {byTheRock: 'apples',byThePuddle: 'pumpkin'},hill: {byTheBench: {leftOfBench: 'pumpkin',rightOfBench: 'pumpkin'},topOfHill: 'apples'},};
  
const pumpkinPicker = (obj) =>
    typeof obj === 'object'
        ? Object.values(obj).reduce((count, value) => count + pumpkinPicker(value), 0 )
        : obj === "pumpkin" ? 1 : 0


let count =   pumpkinPicker(pumpkinPatch); //*answer should prompt => 3*
console.log(count)