RAMESHKUMAR
RAMESHKUMAR

Reputation: 346

search by value which starts with certain string in nested JSON

Example Nested JSON

    {
          "a": "https://example1.com",
          "b": {
            "c":"https://example2.com",
            "d": {
              "e": "www.example3.com"
            }
          },
         "f": {
            "g":"https://example4.com"
          }

        }
      }

Want to filter the values starting with only 'http'. Unable to find any example for nested json.

(optional)Is there a way to achive this in object-scan npm

Expected result

['https://example1.com', 'https://example2.com', 'https://example4.com']

Upvotes: 0

Views: 747

Answers (3)

vincent
vincent

Reputation: 2181

Here is how you would solve this using object-scan (as asked in the question)

// const objectScan = require('object-scan');

const data = { a: 'https://example1.com', b: { c: 'https://example2.com', d: { e: 'www.example3.com' } }, f: { g: 'https://example4.com' } };

console.log(objectScan(['**'], {
  reverse: false,
  filterFn: ({ value }) => typeof value === 'string' && value.startsWith('http'),
  rtn: 'value'
})(data));
// => [ 'https://example1.com', 'https://example2.com', 'https://example4.com' ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/[email protected]"></script>

Disclaimer: I'm the author of object-scan

Upvotes: 1

sfy
sfy

Reputation: 3238

Extract values recursively, flat the array, filter the array by https

const foo = {
  "a": "https://example1.com",
  "b": {
    "c": "https://example2.com",
    "d": {
      "e": "www.example3.com"
    }
  },
  "f": {
    "g": "https://example4.com"
  }

}


function extractValues(data) {
  const run = data => {
    return Object.values(data).map(value => {
      if (typeof value === 'object') {
        return extractValues(value)
      } else {
        return value
      }
    })
  }
  return run(data).flat(Infinity)
}

let a = extractValues(foo).filter(url => /^https/.test(url))

console.log(a)

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

Loop keys, check the type, repeat as needed:

function loopAndParse(thing, rtn) {
    Object.keys(thing).forEach(k => {
        if (typeof thing[k] === "string" && thing[k].indexOf("https://") > -1) 
            rtn.push(thing[k])
        else if (typeof thing[k] === "object") return loopAndParse(thing[k], rtn)
    })
    return rtn;
}

console.log(loopAndParse(obj, []))

Fiddle: https://jsfiddle.net/7megL295/

Upvotes: 1

Related Questions