使用“地址字符串"从json对象获取字段;在JavaScript中 [英] getting a field from a json object using a "address string" in JavaScript

查看:88
本文介绍了使用“地址字符串"从json对象获取字段;在JavaScript中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java脚本的新手,如果这很简单,我深表歉意. 如果我有一个对象,我的问题是句法上的:

I am new to java script , so my apologies if this is trivial. My question is syntactical, if I have an object:

this.state = {
  A : {
       B: {
           C : [
             {value : 'bob'},
             {value : 'Jim'},
             {value : 'luke'},
           ]
       }
  }
}

,我有一个字符串location = 'A.B.C[1]',它描述了我想要的数据的位置.

and I have a string location = 'A.B.C[1]' which describes the location of the data I want.

为什么我不能只做data = this.state[location].value?

是否有使用位置字符串获取数据的简单"JavaScript"方法?

and is there a simple "JavaScript" way of getting the data using the location string?

任何帮助都将是惊人的:)

any help would be amazing :)

推荐答案

您可以拆分路径并缩小对象.

You could split the path and reduce the object.

function getValue(o, path) {
    return path.replace(/\[/g, '.').replace(/\]/g, '').split('.').reduce(function (o, k) {
        return (o || {})[k];
    }, o);
}

var o = { A : { B: { C: [{ value: 'Brenda' }, { value: 'Jim' }, { value: 'Lucy' }] } }};

console.log(getValue(o, 'A.B.C[1]').value); // Jim
console.log(getValue(o, 'A.B.C[0].value')); // Brenda
console.log(getValue(o, 'Z[0].Y.X[42]'));   // undefined

要设置值,您可以拆分路径并通过遍历给定的对象来缩小路径.如果不存在任何对象,请使用名称或数组创建一个新属性.稍后分配值.

For setting a value, you could split the path and reduce the path by walking the given object. If no object exist, create a new property with the name, or an array. Later assign the value.

function setValue(object, path, value) {
    var way = path.replace(/\[/g, '.').replace(/\]/g, '').split('.'),
        last = way.pop();

    way.reduce(function (o, k, i, kk) {
        return o[k] = o[k] || (isFinite(i + 1 in kk ? kk[i + 1] : last) ? [] : {});
    }, object)[last] = value;
}

var test = {};
setValue(test, "foo.name", "Mr. Foo");
setValue(test, "foo.data[0].bar", 100);
setValue(test, "and.another[2].deep", 20);
console.log(test);

这篇关于使用“地址字符串"从json对象获取字段;在JavaScript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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