0

OK, So i remember seeing this somewhere. however can't remember where. I know that there should be a easy way to do this.

Lets say i have the following random object:

{
    people: [
        {
            id: 257293,
            cost: {
                amount: 7,
                currency: 'USD',
            }
        },
        {
            id: 257293,
            cost: {
                amount: 3000,
                currency: 'USD',
            }
        },
    ],
    jobs: [
        {
            name: 'Dentist',
            id: 213213,
            salary: {
                amount: 400,
                currency: 'USD',
            }
        },
        {
            name: 'Soccer player',
            id: 235325,
            salary: {
                amount: 400,
                currency: 'USD',
            }
        },
        {
            name: 'cleaner',
            id: 34734737,
            salary: {
                amount: 400,
                currency: 'USD',
            }
        },
    ],
    food: 'ketchup',
}

And the following key that i need o update a field:

var key = '.jobs#213213.salary.amount';
var update_value = 700;

Is there any easy way to get and update my object? any thoughts or ideas?

Edit: My question is different from this question because arrays i want to access by id of object not array index ('jobs#235325' 235325 is the id property of the inner object).

Edit 2: Since for some reason my question was marked as duplicate (it is not duplicate) i am providing an answer i have found here.

function findById(source, id) {
    for (var i = 0; i < source.length; i++) {
        if (source[i].id === id) {
        return source[i];
        }
    }
}

Object.byString = function(o, s) {
    s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
    s = s.replace(/^\./, '');


    var a = s.split('.');
    for (var i = 0, n = a.length; i < n; ++i) {
        var k = a[i];

        var g = k.split('#');
        if (g) {
            k = g[0];
        }
        if (k in o) {
            o = o[k];
            if (g[1]) {
                o = findById(o, parseInt(g[1]));
            }
        } else {
            return;
        }
    }
    return o;
}
Community
  • 1
  • 1
Aryeh Armon
  • 2,137
  • 2
  • 22
  • 37

0 Answers0