1

I wanna access the properties and their values of an object dynamically, the scenario is:

const SoldeN = {
    1:4,
}
const SoldeN_1 = {
    2:5,
}
const soldes = [
  { formula: '=SoldeN("1")',value:0},
  { formula: '=SoldeN_1("2")',value:0},
  { formula: '=SoldeN_1("1")+SoldeN_1("2")',value:0},
];

What I've tried so far:

const getProperty = string => string.match(/\(.*?\)/g).map(x => x.replace(/[(")]/g, ''))
const getObject = string => string.match(/[=+](.*?)\(/g).map(x => x.replace(/[=(+]/g, ''))
console.log(soldes.map(solde=>[getObject(solde.formula),getProperty(solde.formula)]))
[
  [["SoldeN"], ["1"]],
  [["SoldeN_1"], ["2"]],
  [
    ["SoldeN_1", "SoldeN_1"],
    ["1", "2"],
  ],
];

Till now Everything is ok, but To get the value of an object dynamically based on property I used this function:

const getPropertyValue = (obj, prop) => obj[prop];
getPropertyValue('SoldeN','1')
//'o'

It gives me 'o' instead of 1, I know If I've passed the reference of an object it bring its value; but to get it dynamically I've to pass the actual name of an object which is string, not the object reference. The expected Result would be:

result = [
  { formula: '=SoldeN("1")',value:4},
  { formula: '=SoldeN_1("2")',value:5},
  { formula: '=SoldeN_1("1")+SoldeN_1("2")',value:9},
];

3 Answers 3

1

Why don't you just put your data inside an object and map the data inside loop? There is no need to use eval at all.

const data = {
    SoldeN: {
        1: 4,
    },
    SoldeN_1: {
        2: 5,
    },
};

const soldes = [
    { formula: '=SoldeN("1")', value: 0 },
    { formula: '=SoldeN_1("2")', value: 0 },
    { formula: '=SoldeN("1")+SoldeN_1("2")', value: 0 },
];

const getProperty = string =>
    string.match(/\(.*?\)/g).map(x => x.replace(/[(")]/g, ""));
const getObject = string =>
    string.match(/[=+](.*?)\(/g).map(x => x.replace(/[=(+]/g, ""));

const output = soldes.map(solde => {
    const objs = getObject(solde.formula);
    const props = getProperty(solde.formula);
    const newVal = objs.reduce((carry, item, idx) => {
        carry += data[item][props[idx]];
        return carry;
    }, solde.value);
    return {
        ...solde,
        value: newVal,
    };
});

console.log(output);

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

3 Comments

Perfect and safer than using eval
@TAHERElMehdi, I think you should change accepted answer to my answer because I think eval() is not necessary at all. It may help the future readers to find a proper answer.
Thank you for your answer, anyway your answer is still the best in terms of safety and Security Concerns!
1

You can eval the object name.

const SoldeN = { 1:4 };
const getPropertyValue = (obj, prop) => eval(obj)[prop];
console.log(getPropertyValue('SoldeN','1'));

But be cautious as it is risky! If bad code can get into the eval argument, things can happen.

1 Comment

Thanks for answer, Yes I know it is dangerous to use eval!
1

You can make use of javascript eval method to execute the expression.

Logic

  • Loop through nodes in soldes.
  • Replace all "=" with empty string. "(" with "[" and ")" with "]".
  • This will mmake the expression =SoldeN("1")+SoldeN_1("2") to SoldeN["1"]+SoldeN_1["2"].
  • Evaluating this will give you the expected result.

const SoldeN = {
  1: 4,
};
const SoldeN_1 = {
  2: 5,
};
const soldes = [
  { formula: '=SoldeN("1")', value: 0 },
  { formula: '=SoldeN_1("2")', value: 0 },
  { formula: '=SoldeN("1")+SoldeN_1("2")', value: 0 },
];
const getValue = (formula) => eval(formula.replaceAll("=", "").replaceAll("(", "[").replaceAll(")", "]"));
const result = soldes.map((item) => ({
  formula: item.formula,
  value: getValue(item.formula)
}));
console.log(result);

Please Note Error handling is considered as out of scope.

1 Comment

A smart and effective approach to solving this problem!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.