getting a field from a json object using a “address string” in JavaScript

后端 未结 1 1753
别跟我提以往
别跟我提以往 2020-12-12 01:29

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: {
                   


        
相关标签:
1条回答
  • 2020-12-12 01:38

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

    0 讨论(0)
提交回复
热议问题