getting a field from a json object using a “addres

2020-02-07 05:14发布

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'},
           ]
       }
  }
}

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

Why can I not just do data = this.state[location].value ?

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

any help would be amazing :)

1条回答
够拽才男人
2楼-- · 2020-02-07 05:44

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);

查看更多
登录 后发表回答