0

The following works but I'm trying to find a way to omit the arrayOfObjects[1]['testParent'] = {} bit, imagine you wanted to add a value to an empty object that is nested 10 levels down, you would have to initialize each level with an empty {} first, I'm trying to find a workaround for that.

let arrayOfObjects = [
{},
{},
{},
]

arrayOfObjects[1]['testParent'] = {}
arrayOfObjects[1]['testParent']['testKey'] = 'testValue'

// is there a way to do the above in one line, without having to initialize testParent with an empty object on line 7?

console.log(arrayOfObjects)

1
  • arrayOfObjects[1]['testParent'] = {'testKey': 'testValue'}, like this? Commented Jun 16, 2018 at 19:56

3 Answers 3

2
 arrayOfObjects[1] = {
    testParent: {
      testKey: 'testValue'
    }
 };

In fact, you can avoid the array indexer as well with something like:

 arrayOfObjects = [ 
    {},
    {
      testParent: {
        testKey: 'testValue'
      }
    },
    {}
 ];
Sign up to request clarification or add additional context in comments.

4 Comments

This is not JSON.
@lonesomeday: because it is missing all the quotes, I suppose? I've removed the reference to JSON.
No, because JSON is a format for data serialisation. This is just standard Javascript object syntax. Downvote removed, in any case.
This seems like the way to go for an arbitrary nesting, keeping it simple, etc. arrayOfObjects[1] = {testParent:{testParent:{testKey: 'testValue'}}}
0

You can create custom method for this, using reduce that takes string and value and sets nested property.

let arr = [{}, {}, {}]

function set(obj, key, value) {
  key.split(".").reduce((r, e, i, a) => {
    return r[e] || (r[e] = a[i + 1] ? {} : value)
  }, obj);
}

set(arr, "0.testParent.testKey", "testValue")
set(arr, "2.a.b.f", "value")
set(arr, "2.a.b.c", "value")

console.log(arr)

Comments

0

Maybe a small helper can help you to omit the brackets:

const $ = (obj, key, ...keys) => key != undefined ? $(obj[key] || (obj[key] = {}), ...keys) : obj;

Usable as:

const arr = [];
$(arr, 1, "testParent").testKey = "testValue";

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.