Home > Back-end >  Find elements from concatenate strings in JS
Find elements from concatenate strings in JS

Time:08-03

How can I search the values in an Object from strings, something like:

const query = "['arg1']['arg2']"

const renderImage = async (index) => {

    const data = await fetchImage(index)
    const image = document.querySelector('.div')
    
    image.setAttribute("src", data`${query}`)

}

The fetch function is perfect working.

Edit:

The image source is in the data['arg1']['arg2']. If I use image.setAttribute("src", data['arg1']['arg2']) the code runs fine, but I need to do this dynamically and concatenate strings will help me.

Summing up: can I get the same result data['arg1']['arg2'] concatenating object and "query" (['arg1']['arg2'])?

CodePudding user response:

you can store the path as an array of keys and access it like this

const query = ['arg1', 'arg2']
...
    image.setAttribute("src", query.reduce((o, k)=>o[k], data))

CodePudding user response:

It seems you are trying to extract the property names you want, from a poorly formatted string. Ideally, you would get query into a better format to begin with, so you don't have to parse the string. For instance, if you could get query as two separate variables:

const query1 = 'arg1';
const query2 = 'arg2';
image.setAttribute("src", data[query1][query2]);

you could also store query in a better data type to do this, like const query = { arg1: 'arg1', arg2: 'arg2' }; then access with dot syntax data[query.arg1][query.arg2].

But if you must keep query as this weirdly formatted string for some reason, you can do something like this, parsing the string into it's parts, putting them into an array, then using the array to access the right data within data.

let query = "['arg1']['arg2']";
query = query.slice( 2 ).slice( 0, -2 ).split( "']['" );
image.setAttribute( "src", data[query[0]][query[1]] );
  • Related