且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用特定键(深键)将所有值从JSON对象放入数组

更新时间:2023-02-23 08:09:24

使用 Object.keys 像这样:

function getText(obj) {
  let text = [];
  Object.keys(obj).forEach(key => {
    if (key == "_text") {
      text.push(obj[key]);
    }
    if (typeof obj[key] == "object") {
      text.push(getText(obj[key]));
    }
  });
  const flatten = function(arr, result = []) {
    for (let i = 0, length = arr.length; i < length; i++) {
      const value = arr[i];
      if (Array.isArray(value)) {
        flatten(value, result);
      } else {
        result.push(value);
      }
    }
    return result;
  };
  return flatten(text);
}

const myObj = {
  object1: {
    deeperLevel: {
      _text: "Some text"
    }
  },
  object2: {
    _text: "that I want"
  },
  object3: {
    deeperLevel: {
      EvenDeeper: {
        _text: "in an array"
      }
    }
  }
};

const myArr = getText(myObj);

console.log(myArr);

来自此答案的过滤算法