2

When loading JSON from a server, I need to create objects. The objects do not always exist beforehand.Therefore I have to check that each level exists before adding a new level. Is there a better way to do this, then the following way:

var talkerId = commentDB.val().to;
var commentId = commentDB.val().id

if (!store.talkers.hasOwnProperty(talkerId)) {
    store.talkers[talkerId] = {}
}
if (!store.talkers[talkerId].hasOwnProperty(comments)) {
    store.talkers[talkerId] = { comments: {} };
}
if (!store.talkers[talkerId].comments.hasOwnProperty(commentId)) {
    store.talkers[talkerId].comments[commentId] = {}
}
store.talkers[talkerId].comments[commentId].author = commentDB.val().author;
5
  • 2
    See lodash.set. Commented Mar 26, 2018 at 12:00
  • Could you not simply return JSON from the server and then use JSON.parse() to convert to an object? Commented Mar 26, 2018 at 12:01
  • I can't return from the server, because I join two fields of data, and create combined JSON in the client. Commented Mar 26, 2018 at 12:14
  • So you make 2 calls to the server, each of them making a DB call, then you return 2 datasets to the client and that merges them into one object? Commented Mar 26, 2018 at 12:18
  • @31piy, it did the job :-) Commented Mar 26, 2018 at 12:27

3 Answers 3

2

You cour reduce the keys by using the object an check if the key exist. if not create a new property with an empty object.

var dbValue = commentDB.val();

[dbValue.to, 'comments', dbValue.id].reduce(
    (o, k) => o[k] = o[k] || {},
    store.talkers
).author = commentDB.val().author;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, very cool, but reduce has logic that I find hard to follow when maintaing a code
1

Why don't you create a function

function checkAndCreateProperty(arr, baseVar) {
   for(var i = 0; i < arr.length; i++) {
       if (!baseVar.hasOwnProperty(arr[i])) {
           baseVar[arr[i]] = {};
      }
      baseVar = baseVar[arr[i]];
   }
}


checkAndCreateProperty(["talkerId", "comments", commentDB.val().id, commentDB.val().author], store.talkers)

Comments

1

After the suggestion of @31piy I went for the most simple solution:

using lodash _.set

var talkerId = commentDB.val().to;
var commentId = commentDB.val().id;

_.set(store.talkers, '[' + talkerId + '].comments[' + commentId + '].author', commentDB.val().author)

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.