Skip to content

Instantly share code, notes, and snippets.

@agusputra
Last active May 13, 2016 00:54
Show Gist options
  • Select an option

  • Save agusputra/43d373dc3ec883688f3a4af1d7ebdf29 to your computer and use it in GitHub Desktop.

Select an option

Save agusputra/43d373dc3ec883688f3a4af1d7ebdf29 to your computer and use it in GitHub Desktop.
Access or Compose object using string literal. ex: '1.2.3' => {"1": {"2": {"3": "0"}}}
'use strict';
const state = {
a: {
aa: {
aaa: 'AAA'
},
ab: {
aab: 'AAB'
}
}
};
function accessObject(context, properties, value) {
properties = properties.split('.');
let head = context;
context = head;
for (let i = 0; i < properties.length; i++) {
if (i === properties.length - 1) {
context[properties[i]] = value;
break;
}
context = context[properties[i]];
}
return head;
}
function composeObject(properties, value) {
properties = properties.split('.');
let head = {};
let context = head;
for (let i = 0; i < properties.length; i++) {
if (i === properties.length - 1) {
context[properties[i]] = value;
break;
}
context = context[properties[i]] = {};
}
return head;
}
const result1 = accessObject(state, 'a.aa.aaa', 'foo');
const result2 = composeObject('a.aa.aaa', 'foo');
console.log(JSON.stringify(result1, null, 1));
console.log(JSON.stringify(result2, null, 1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment