JS获取数组子节点数据

时间:2019-05-25 04:32:21

标签: javascript arrays

我得到了一个数组列表,像下面的数据。我要创建一个函数,输入一个类似“ 203”的数字,然后该函数将返回2个值“ John”和“ d”,但我不知道该怎么做。

当我在浏览器开发人员工具控制台中键入console.log(data.i)时,会有一个返回值,但在实际代码执行中什么都没有显示。

var data = {
  "John": {
    "a": "200",
    "b": "201",
    "c": "202",
    "d": "203",
    "e": "204",
    "f": "205"
  },
  "Allen": {
    "y": "100",
    "z": "103"
  }
}
for (i in data) {
  console.log(i); // return John, Allen...
  for (var j in data.i) {
    console.log(j[0]); //return nothing
  }
}

3 个答案:

答案 0 :(得分:2)

您需要使用括号表示法,例如data[i]。进一步了解Property Accessors

var data={
"John":{"a":"200","b":"201","c":"202","d":"203","e":"204","f":"205"},
"Allen":{"y":"100","z":"103"}
};

var input = "203";

function findVal(obj, val) {
  var result;
  for (var i in obj) {
    for (var j in data[i]) {
      if(data[i][j] === val) {
        result = {"key1" : i, "key2" : j};
      }
    }
  }
  return result;
}

console.log(findVal(data, input));

答案 1 :(得分:1)

在每个嵌套循环中,您可以将该键上的元素与给定的输入进行比较,然后记录该键

var data = { "John": { "a": "200", "b": "201", "c": "202", "d": "203", "e": "204", "f": "205" }, "Allen": { "y": "100", "z": "103" } }
let input = "203"

for (i in data) {
  for (var j in data[i]) {
    if(data[i][j] === input) console.log(j)
  }
}

我更喜欢的方法是使用key value的数组组成的数组,然后在该数组上使用find。

var data = { "John": { "a": "200", "b": "201", "c": "202", "d": "203", "e": "204", "f": "205" }, "Allen": { "y": "100", "z": "103" } }
let input = "203"

let res = (Object.values(data)
               .flatMap(Object.entries)
               .find(([_,v]) => v === input) || {}
          )[0];
console.log(res)

答案 2 :(得分:1)

在这种情况下,这可能是一个过大的杀伤力,但以防万一您将来需要超越目前的2个等级。

此方法使用递归收集所有找到的匹配,并返回一个数组(或者在这种情况下,我加入了all以给您一个字符串)。它还支持多个匹配:

var data = {
  "John": {
    "a": "200",
    "d": "203",
    "aa": {
      "z": "443",     // 3rd level
      "aaa": {
        "y": "331",   // 4th level etc...
        "z": "443"
      }
    }
  },
  "Allen": {
    "z": "103"
  }
}

const search = (obj, text) => {
  let hits = []
  const flatSearch = (obj, text = '', hits = [], path = null) =>
    Object.entries(obj).forEach(([key, value]) => {
      if (typeof value == 'object')
        flatSearch(value, text, hits, path ? `${path}.${key}` : key)
      else
        if (value.toString().toLowerCase().includes(text.toLowerCase()))
          hits.push([...path.split('.'), key])
    })
  flatSearch(obj, text, hits)
  return hits.map(x => x.join(' & ')).join(', ')  // Format the final output
}

console.log(search(data, '203'))  // Single hit
console.log(search(data, '331'))  // Single hit
console.log(search(data, '443'))  // Multi hit