Access a property of an object from a string array

4

I have a object like this:

{
  var: {
    foo: '',
    foo2: '',
  }
}

and a parameter (['var', 'foo2'], newData) comes to me in a function. What would I have to do to return the original object with var.foo2 = new Data ?

The parameter amount of the array as well as the general object may change: (

I've tried:

let fields = ['var', 'foo2'];
let obj = objOri;
for (let f of fields) {
  if (obj.hasProperty(f)) {
    obj = obj[f];
  }
}
obj = newData;
console.log(objOri);// Sigue saliendo mal :(
    
asked by Moises 06.09.2018 в 10:29
source

4 answers

1

In this line you assign to the variable obj what is in objOri, to then go through all the fields and, presumably, go down level within that object:

let obj = objOri;
for (let f of fields) {
  if (obj.hasProperty(f)) {
    obj = obj[f];
  }
}

This works to read the current property value but you can not replace it as you do at the end. What you could try is to go through all the fields and stay with the last to do something like this:

let obj = objOri;
let objFormer = null;
let lastField = null;
for (let f of fields) {
  if (obj.hasProperty(f)) {
    objFormer = obj;
    lastField = f;
    obj = obj[f];
  }
}
objFormer[lastField] = newData;

This is a very rudimentary code. I think it is more than improvable but it is the first thing that has occurred to me

    
answered by 06.09.2018 в 10:55
1

What you need has a recursive nature. Your Add function may look like this (passing the original object as a reference). You can use as many levels as you want in the tree.

var objOrig = { 
  'var': {
    foo: '',
    foo2: ''
  }
}

function Agregar(obj, arr, fn) {
   if(arr.length) {
      var prop = arr.shift();
      if(arr.length) Agregar(obj[prop], arr, fn); else obj[prop] = fn;
   } 
}

Agregar(objOrig, ['var','foo2'], function() { console.log("hey"); });

console.log(objOrig);

// { var { foo: "", foo2: f() } }
    
answered by 06.09.2018 в 13:18
0

I have solved it like this: D

let obj = {a: {a: {a: 'aaa'}, b: 'ab'}, b: 'b', c: {a: 'ca', b: 'cb'}};
let fields = ['a', 'b'];
function replaceValue(obj, fields, newValue) {
  let objClone = {};
  let field = fields.shift();
  for (let key in obj) {
    if (key === field) {
      if (typeof obj[key] === 'object' && fields.length > 0) {
        objClone[key] = replaceValue(obj[key], fields, newValue);
      } else {
        objClone[key] = newValue;
      }
    } else {
      objClone[key] = obj[key];
    }
  }
  return objClone;
}
console.log(obj);
obj = replaceValue(obj, fields, 'mou');
console.log('resultado', obj);
    
answered by 06.09.2018 в 11:34
0

I work with vue js and this is common because I work with laravel. What I do is a simple one.

Json.parse ();

And each property of the collection becomes accessible as if it were an object.

    
answered by 06.09.2018 в 13:30