getPathValue() function for deep objects

后端 未结 2 881
深忆病人
深忆病人 2021-01-26 11:52

This is a follow-up question to this: getPathValue() function for deep objects with arrays and with packed JSON

The accepted answer works very well in most situations:

2条回答
  •  轮回少年
    2021-01-26 12:02

    Change:

    .split('.')
    

    By:

    .split('.').filter(Boolean)
    

    It will remedy a dot that got placed at the very beginning of the string, which is what happens when the input starts with a [, like in [0].

    Demo:

    function getPathValue(object, path) {
        return path
           .replace(/\[/g, '.')
           .replace(/\]/g, '')
           .split('.').filter(Boolean)
           .reduce(function (o, k) {
               return (typeof o === 'string' ? JSON.parse(o) : (o || {}))[k];
           }, object);
    }
    
    var obj = [{"currencyPair":"EUR/USD","timestamp":"1546028298698","bidBig":"1.14","bidPips":"450","offerBig":"1.14","offerPips":"457","high":"1.14253","low":"1.14732","open":"1.14305"},{"currencyPair":"USD/JPY","timestamp":"1546028299095","bidBig":"110.","bidPips":"326","offerBig":"110.","offerPips":"336","high":"110.222","low":"111.062","open":"111.012"}];
    
    value = getPathValue(obj, '[0].bidPips');
    
    console.log(value);

    It can be done easier though, by replacing the replace and split calls by one match call:

    function getPathValue(object, path) {
        return path
           .match(/[^[\].]+/g)
           .reduce(function (o, k) {
               return (typeof o === 'string' ? JSON.parse(o) : (o || {}))[k];
           }, object);
    }
    
    var obj = [{"currencyPair":"EUR/USD","timestamp":"1546028298698","bidBig":"1.14","bidPips":"450","offerBig":"1.14","offerPips":"457","high":"1.14253","low":"1.14732","open":"1.14305"},{"currencyPair":"USD/JPY","timestamp":"1546028299095","bidBig":"110.","bidPips":"326","offerBig":"110.","offerPips":"336","high":"110.222","low":"111.062","open":"111.012"}];
    value = getPathValue(obj, '[0].bidPips');
    
    console.log(value);

提交回复
热议问题