gpt4 book ai didi

javascript - 为大型嵌套对象实现对象迭代器的问题

转载 作者:行者123 更新时间:2023-11-30 19:44:23 25 4
gpt4 key购买 nike

假设有一个对象,我们正在尝试编写一个函数,将“路径”作为参数并打印其中的任何内容。如果输入无效,则抛出错误。对象大小可能很大。

const obj = {
test: {
demo: [{
lname: 'dave'
}]
}
};

function getData(obj, dest) {
const path = dest.split('.');
return helper(obj, path);

function helper(obj, path) {
if (!path.length) return obj;
const cur = path.shift();

if ((Array.isArray(obj) && typeof obj === 'string') ||
(typeof obj === 'undefined')) {
throw new Error("Something wrong")
}

obj = obj[cur];
return helper(obj, path);
}
}

console.log(getData(obj, 'test.demo.0.lname'));
//console.log(getData(obj, 'test.demo.dave.lname')); // throws an error since in demo array you can't access 'dave'

我想弄清楚编写此方法的更短方法是什么?我听到有人说我们可以写几行。

最佳答案

一个简单而简短的实现可以使用 Array#reduce迭代地从一个对象上取下键,如下所示:

const obj = {
test: {
demo: [{
lname: 'dave'
}]
}
};

function getData(obj, dest) {
var keys = dest.split(".");
return keys.reduce(function(currentObject, key) {
if(typeof currentObject == "undefined") throw Error("Something wrong");
return currentObject[key];
}, obj)
}

console.log(getData(obj, 'test.demo.0.lname'));
console.log(getData(obj, 'test.demo.dave.lname')); // throws an error since in demo array you can't access 'dave'

这是更冗长的选项,为了演示正在发生的事情,您可以进一步缩短它

const obj = {
test: {
demo: [{
lname: 'dave'
}]
}
};

function getData(obj, dest) {
return dest.split(".").reduce((curr, key) => curr[key], obj)
}

console.log(getData(obj, 'test.demo.0.lname'));
console.log(getData(obj, 'test.demo.dave.lname')); // throws an error since in demo array you can't access 'dave'

您还可以避免抛出错误,但如果找不到键则简单地返回 undefined

const obj = {
test: {
demo: [{
lname: 'dave'
}]
}
};

function getData(obj, dest) {
return dest.split(".").reduce((curr, key) => curr != undefined ? curr[key] : undefined, obj)
}

console.log(getData(obj, 'test.demo.0.lname'));
console.log(getData(obj, 'test.demo.dave.lname')); // undefined

然而,虽然这很容易实现,但它是以错误检查为代价的。调试到底出了什么问题可能真的很烦人,因为您必须知道数据对象和目标输入是什么,然后尝试手动找出丢失的键。因此,如果您想要更健壮和灵活的代码,通常实现时间越长越好。

如果您使用的是 Lodash,那么您可以使用他们的 _.get它更加健壮并处理更多语法

const obj = {
test: {
demo: [{
lname: 'dave'
}]
}
};

console.log(_.get(obj, 'test.demo.0.lname'));
console.log(_.get(obj, 'test.demo[0].lname'));
console.log(_.get(obj, ['test', 'demo', 0, 'lname']));

console.log(_.get(obj, 'test.demo.dave.lname')); // undefined

console.log(_.get(obj, 'test.demo.dave.lname', 'this is not dave but the default vale'));
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

关于javascript - 为大型嵌套对象实现对象迭代器的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55073362/

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