0

somewhere from the API data I am getting normal string like, “Hi ${person[0].name}” now this string I am converting into template string and getting replace its variables from array of object.

Here is snippet which I am trying to execute, and I am not getting expected output

const getObjPath = (path, obj, fallback = `$\{${path}}`) => {
    if (path && obj) return path.split('.').reduce((res, key) => res[key] || fallback, obj);
    return path;
};
const interpolate = (template, variables, fallback) => {
    const regex = /\${[^{]+}/g;
    if (template && variables) {
        return template.replace(regex, (match) => {
            let path = match.slice(2, -1).trim();
            path = path.split('|').map((item) => item.trim());
            const fieldValue = getObjPath(path[0], variables, fallback);
            if (fieldValue) return fieldValue;
            return path[1] || fallback;
        });
    }
    return template;
};

const data = { person: [{ name: 'John', age: 18 }] };
const a = interpolate('Hi ${person?.[0]?.name | text} (${person?.[0]?.age | text})', data);
console.log(a);

output: "Hi ${person?.[0]?.name} (${person?.[0]?.age})"

expected output: "Hi John 18"

Can someone tell me what I am doing wrong here?

0

1 Answer 1

1

The problem is that your path splitting in getObjPath does not deal with square brackets in the path.

So replace this

path.split('.')

with:

path.match(/[^.[\]]+/g)

const getObjPath = (path, obj, fallback = `$\{${path}}`) => {
    if (path && obj) return path.match(/[^.[\]]+/g).reduce((res, key) => res[key] || fallback, obj);
    return path;
};
const interpolate = (template, variables, fallback) => {
    const regex = /\${[^{]+}/g;
    if (template && variables) {
        return template.replace(regex, (match) => {
            let path = match.slice(2, -1).trim();
            path = path.split('|').map((item) => item.trim());
            const fieldValue = getObjPath(path[0], variables, fallback);
            if (fieldValue) return fieldValue;
            return path[1] || fallback;
        });
    }
    return template;
};

const data = { person: [{ name: 'John', age: 18 }] };
const a = interpolate('Hi ${person[0].name | text} (${person[0].age | text})', data);
console.log(a);

Sign up to request clarification or add additional context in comments.

2 Comments

sorry @trincot , I missed that I am using elvis also ${person?.[0]?.name}
Ok, but that was not your question. The question as to why nothing got changed has been answered. Now you should try to implement the logic to deal with ?.. If you bump into an issue in doing so, then feel free to ask a new question about that aspect. But you should at least have done an effort.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.