This question already has answers here:
How can I access and process nested objects, arrays or JSON?
                                
                                    (25个答案)
                                
                        
                3年前关闭。
            
        

我需要对可以包含嵌套对象和数组的javascript对象进行深层迭代,并且需要对所有数值执行函数并修改该对象。

例如,假设我需要将每个数字乘以2。

const foo = (obj) => {
    // multiply every numeric value by 2
};

const modified = foo({
    a: 0,
    b: 3,
    c: {
      d: 4,
      e: {
          f: 6,
          g: [ 0, 3, 7, 3 ]
      }
    }
});


修改的值应为:

{
    a: 0,
    b: 6,
    c: {
      d: 8,
      e: {
          f: 12,
          g: [ 0, 6, 14, 6 ]
      }
    }
}


由于人们通常想知道您的尝试,因此这是我在完全陷入困境之前走了多远。

const obj = {};
for(key in object) {
    const item = object[key];
    if(typeof item === 'object') {
        // The levels deep is dynamic, so how would I keep doing this..
    } else if(typeof item === 'array') {
        obj[key] = item.map((a, b) => a * 2);
    } else if(!isNaN(item)) {
        obj[key] = item * 2;
    }
}

最佳答案

使用递归并扩展您的解决方案

function multiplyByTwo(objectToParse) {
  const obj = {};
  for (key in objectToParse) {
    const item = object[key];
    if (typeof item === 'object') {
        obj[key] = multiplyByTwo(item);
    } else if (typeof item === 'array') {
      obj[key] = item.map((a, b) => a * 2);
    } else if (!isNaN(item)) {
      obj[key] = item * 2;
    }
  }
  return obj;
}

const result = multiplyByTwo(object);

关于javascript - 遍历整个javascript对象并修改类型为[duplicate]的所有值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43432619/

10-11 23:23
查看更多