1

I need to treat array values as props of object. For example:

let arr = ['masa_icerik', 'urunler', 0, 'urun_adet'];
let obj = {
  "_id": "5c13bd566704aa5e372dddcf",
  "masa_id": 3,
  "masa_numara": 3,
  "masa_magaza": 1,
  "masa_icon": "kola",
  "masa_adi": "salon 3",
  "masa_durum": 1,
  "masa_icerik": {
    "adisyon": "J1554745811908",
    "urunler": [{
      "urun_adet": 14,
      "urun_fiyat": 3,
      "urun_id": "5c16686b93d7b79ae6367864",
      "urun_odenen": 0
    }, {
      "urun_adet": 1,
      "urun_fiyat": 5,
      "urun_id": "5c16686b93d7b79ae6367865",
      "urun_odenen": 0
    }]
  },
  "masa_acilis": "2019-04-08T17:50:12.052Z",
  "masa_acan": "5c1eda01d1f4773110dd6ada"
};

I have an array and an object like above and I want to do something like this:

let res;
arr.forEach(elem => {
   res = obj[elem];
});

and after that I need to get something like :

obj['masa_icerik']['urunler'][0]['urun_adet']

The number of the values is dynamic from server. Thats why i need something like this. Is there any way to do that? I need to change that property and return the changed obj.

4 Answers 4

1

You can use forEach loop to loop thru the array and store it to a temp variable. If all elements exist, it will change the value.

let arr = ['a', 'b', 'c'];
let obj = {'a':{'b':{'c':1}}};
let newValue = "NEW VALUE";

let temp = obj;
arr.forEach((o, i) => {
  if (i < arr.length - 1) temp = temp[o] || null;
  else if (temp !== null && typeof temp === "object" ) temp[o] = newValue;
});

console.log(obj);


If there are multiple multiple object properties missing in the last part of the array.

let arr = ['a', 'b', 'c', 'd'];
let obj = {'a': {'b': {}}};
let newValue = "NEW VALUE";

let temp = obj;
arr.forEach((o, i) => {
  if (i < arr.length - 1) {
    if (!temp[o]) temp[o] = {[arr[i + 1]]: {}};
    temp = temp[o];
  } else if (temp !== null && typeof temp === "object") temp[o] = newValue;
});

console.log(obj);

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

15 Comments

I need to set that value of object. Not to get it. Sorry for misleading question.
On side note: you should consider undefined cases, i mean arr input like [1,2,3]
@Code Maniac Yes I have a value like 0 in my array
@CodeManiac, I'm about to post that code. But user don't need the first code. So don't need to post it :)
Just posted it. :)
|
0

You can use references

Here idea is

  • Initialize val with object reference
  • Loop through array and keep setting new reference to val

let arr = ['a','b','c'];
let obj = {'a':{'b':{'c':1}}};

let getMeValue = (arr) => {
  let val=obj;
  arr.forEach(e => val = val && val[e] )
  return val
}

console.log(getMeValue(arr))
console.log(getMeValue([1,2,3]))

UPDATE: I want to change values

let arr = ['a','b','c'];
let obj = {'a':{'b':{'c':1}}};

let getMeValue = (arr) => {
  let val = obj
  arr.forEach((e,i) => {
  if(i === arr.length-1 && val){
    val[e] = 5
   }
  else {
  val = val && val[e]
  }
 })
 return obj
}

console.log(getMeValue(arr))

6 Comments

I need to set that value of object. Not to get it. Sorry for misleading question.
@İsmailFurkanGÖKHASAN what do you mean ? you want to change the value of object ?
I need to change the object like obj['a']['b]...['n'] = 'someValue'; @Code Maniac
@İsmailFurkanGÖKHASAN you can try the second snippet
I need to return the original object with changed value.
|
0

I am not fully understanding where you are getting the new values from but I think this will get you on the right track.

let newObj = {};

arr.map(each => {
   newObj[each] = "new value";
 })

console.log(newObj);

Comments

0

I'm not sure about your requirment here, I guess you want the below:

    let func = (arr, value)=>{
        r = {};
        r[arr[arr.length-1]] = value;
        for(let i = arr.length-2; i>=0; i--){
            obj = {};
            obj[arr[i]] = r;
            r = obj;
        }
        return r;
    }
    console.log(func(['a', 'b', 'c'], 1));

Comments

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.