Home > Blockchain >  access the properties and their values of an object dynamically in JavaScript
access the properties and their values of an object dynamically in JavaScript

Time:12-28

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},
];

CodePudding user response:

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);

CodePudding user response:

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.

CodePudding user response:

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.

  • Related