0

I just came to this question solution and I have seen that many times as a recursive method that it is very elegant. Though since I want to do this inside a promise. Does anybody knows how to iterate nested objects properties on a non recursive way? I did a function that really sucks just for the case for one nested property: (it returns a promise)

export function setValue(propertyPah, value, obj) {
  console.log("setting the value of the property")

  let properties = propertyPah.split(".")

  if (properties.length > 1) {//not the last property
    let nestObject = obj[properties[0]]
    nestObject[properties[1]] = value
  } else {//last property
    obj[properties[0]] = value
  }
  return Promise.resolve(obj)
}

Now I need for three nested properties... so I want to write a generic one. Needless to say I am not an expert in JavaScript.

Juanjo
  • 670
  • 7
  • 17
  • 5
    There's no reason to return a promise here, the operation isn't asynchronous. If you really want to return a promise, though, use the recursive function and then write a promise wrapper for it (or just wrap the result). – T.J. Crowder Jun 13 '18 at 18:45
  • Thanks @T.J.Crowder I never thought of that – Juanjo Jun 13 '18 at 19:13
  • Hi @T.J.Crowder. Can you post that as an answer so I can upvote it and mark it as an answer. I am sure people with the same question will learn a lot from this. Many Thanks – Juanjo Jun 13 '18 at 19:26
  • Also, every recursive implementation can be replaced with a stack-based implementation. – Felix Kling Jun 13 '18 at 20:09
  • Hi - Thanks, but I think you're probably better off just deleting the question. I don't think it'll help future readers. Happy coding! – T.J. Crowder Jun 14 '18 at 11:54

1 Answers1

-1

You should use jsonpath-plus library to manipulate the complex JSON objects. It allows you to write path patters and queries to manipulate the JSON object.

I hope this solves your query.

Hriday Modi
  • 2,001
  • 15
  • 22