最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Access dynamic nested key in JS object - Stack Overflow

programmeradmin2浏览0评论

I have an array like ['animals', 'cats', 'cute', 'fast', 'small', ...], and want to access nested keys of the object like

let object = {
  one: {
    two: {
      three: {
        // and so on
      }
    }
  }
}

Usually I would write object['animals']['cats']['cute']['fast']['small']..

The problem is that keys and the number of levels are dynamic (so I can get objects with 2 nested levels or 50), so I have no idea how it can be done

Thanks in advance for any help

I have an array like ['animals', 'cats', 'cute', 'fast', 'small', ...], and want to access nested keys of the object like

let object = {
  one: {
    two: {
      three: {
        // and so on
      }
    }
  }
}

Usually I would write object['animals']['cats']['cute']['fast']['small']..

The problem is that keys and the number of levels are dynamic (so I can get objects with 2 nested levels or 50), so I have no idea how it can be done

Thanks in advance for any help

Share Improve this question asked Jan 17, 2020 at 23:09 Max MikhalchukMax Mikhalchuk 1051 gold badge2 silver badges11 bronze badges 2
  • which part is known, the key you want to extract from the object, or the structure of the object itself? – Michael Rodriguez Commented Jan 17, 2020 at 23:13
  • @MichaelRodriguez while writing code - nothing, while script running - everything (how many levels, what key on each level and of course I have access to the object) – Max Mikhalchuk Commented Jan 17, 2020 at 23:17
Add a ment  | 

1 Answer 1

Reset to default 11

Iterate over the array of keys with .reduce, where the accumulator is the current nested object:

let object = {
  one: {
    two: {
      three: {
        prop: 'val'
      }
    }
  }
};

const props = ['one', 'two', 'three', 'prop'];
const nestedVal = props.reduce((a, prop) => a[prop], object);
console.log(nestedVal);

To assign a value at the same point, first pop off the last key, use the same reduce trick to get to the last object, and assign to the property at the last key with bracket notation:

let object = {
  one: {
    two: {
      three: {
        prop: 'val'
      }
    }
  }
};

const props = ['one', 'two', 'three', 'prop'];
const lastKey = props.pop();
const nestedObj = props.reduce((a, prop) => a[prop], object);
nestedObj[lastKey] = 'newVal';
console.log(object);

发布评论

评论列表(0)

  1. 暂无评论