javascript - "Object.Key"使用 map 搜索

标签 javascript

老实说,我不知道如何在标题中解释这一点,但我尽力了。我想要做的是从字符串中获取所有对象/值。但是,由于我的对象可以包含对象,所以我想确保它也能正常工作。这就是我想要实现的目标:

var key = "House.Number";
var data = "...";
var output = data.map(item => item[key]);

这应该做的是给我所有门牌号。简单地执行 item["House.Number"] 是行不通的,但是如果我执行 item["House"]["Number"] 就可以了。有没有快速/好的方法来做到这一点? split on . 是指新对象还是类似的东西?

https://jsfiddle.net/psz4Ltqa/1/

最佳答案

你可以像这样拆分到一个路径并循环遍历键:

var data = {
  One: {
    Two: {
      Three: 3
    }
  }
}

var getPath = function(obj, path) {
  return path
    .split(".") // Create an array of keys
    .reduce(function(pos, k) {
      return pos.hasOwnProperty(k) ? pos[k] : pos; // Return nested value or, if there isn't, last value
    }, obj);
}

console.log(getPath(data, "One.Two"));
console.log(getPath(data, "One.Two.Three"));

(请注意,您可以自行决定在缺少路径时要执行的操作。例如,您可以返回 undefined,或者像我选择的那样,返回您可以找到的最后一个值)

现在,您可以像这样在 map 操作中使用它:

// Switched the argument order to make it more suitable for `map` (data last)
var getPath = function(path, obj) {
  return path
    .split(".") // Create an array of keys
    .reduce(function(pos, k) {
      return pos.hasOwnProperty(k) ? pos[k] : pos; // Return nested value or, if there isn't, last value
    }, obj);
};

var testData = [
  { One: { Two: { Three: "Three" } } },
  { One: { Two: { Three: 3 } } },
  { One: { Two: { Three: "11" } } }
];

var oneTwoThrees = testData.map(getPath.bind(null, "One.Two.Three"));

console.log(oneTwoThrees);

如果你不喜欢 bind 语法,你可以柯里化(Currying)函数:

// getPath now returns a function that wraps the path in its closure and waits for the object to get its data from
var getPath = function(path) {
  return function(obj) {
    return path
      .split(".") // Create an array of keys
      .reduce(function(pos, k) {
        return pos.hasOwnProperty(k) ? pos[k] : pos; // Return nested value or, if there isn't, last value
      }, obj);
  };
};

var testData = [
  { One: { Two: { Three: "Three" } } },
  { One: { Two: { Three: 3 } } },
  { One: { Two: { Three: "11" } } }
];

var oneTwoThrees = testData.map(getPath("One.Two.Three"));

console.log(oneTwoThrees);

关于javascript - "Object.Key"使用 map 搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41459403/

相关文章:

javascript - 在输入(数字)的按键上添加/删除输入(文本)

javascript - 悬停在一个类(class)而不是另一个类(class)正常工作

javascript - YouTube "stats for nerds"是如何工作的。或者如何从 JavaScript 获取正在播放的视频的编解码器信息

javascript - 为 AWS S3 的多个对象创建多个签名 url

javascript - 如何将叠加层与悬停图标列表对齐- JS/CSS

javascript - 使用 `status == true` 时, boolean 条件始终为假

javascript - 获取子数组中的项目并放回主数组

javascript - 如何点击没有固定类别值的按钮?但它有一个固定的 'data-testid'

javascript - 数组将js中的数组插入php中的变量

javascript - 如何从 jQuery DataTables 单元格内的 <input type=date> 获取值?