使用 props 访问纯文本或数组中的对象路径 [英] Access object path in plain text or array with props

查看:30
本文介绍了使用 props 访问纯文本或数组中的对象路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑波纹管对象和存储在对象内的值的路径:

Consider the bellow object and a path to a value stored inside object:

var obj = { a: 1, b: { a: { x: 2 }, b: 3 }, c: 4 }
var path = ["b", "a", "x"];

在对象路径中获取内容的最佳方式(最佳性能)是什么?

What is the best way (best performance) to get the content in object path?

使用 eval()

path = ["obj"].concat(path);
var value = eval(path.join("."));

循环

var _obj = obj;
for(key in path) {
    _obj = _obj[path[key]];
}
var value = _obj;

有没有其他更好的方法来存储和查询复杂的对象?

Is there any other better way to store and query a object complex?

推荐答案

你可以走这条路并使用 Array#reduce 用于对象.

You could take the path and use Array#reduce for the object.

function getValue(object, path) {
    return path.reduce(function (o, k) {
        return (o || {})[k];
    }, object);
}

var obj = { a: 1, b: { a: { x: 2 }, b: 3 }, c: 4 }
    path = ["b", "a", "x"];

console.log(getValue(obj, path));

这篇关于使用 props 访问纯文本或数组中的对象路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆