gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:00:15 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com