I have array like this
var object_ = [
{
"name":"Akshay"
}
];
var object_keys = "[0]['other_data']";
Correct way is like this to add the sub data
object_[0]['other_data'] = {
"age":20,
"Sex": "male"
}
My question is Can i do something like this ?
object_[object_keys] = {
"age":20,
"Sex": "male"
}
CodePudding user response:
Lodash's _.set
method achieves this:
var object_ = [{
"name": "Akshay"
}];
_.set(object_, "[0]['other_data']", {
"age": 20,
"Sex": "male"
})
console.log(object_)
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
CodePudding user response:
One strategy might be to store your keys in an array rather than a string, and reference each key by index:
let object_ = [{
"name": "Akshay"
}];
const object_keys = [0, 'other_data'];
object_[object_keys[0]][object_keys[1]] = {
"age": 20,
"Sex": "male"
};
console.log(object_);
CodePudding user response:
If you don't mind using [0, 'other_data']
instead of "[0]['other_data']"
you can easily write a generic function that takes an object, key array and a value. Then sets the value based on the given key array (aka key path).
function setValue(object, keys, value) {
if (!keys.length) return; // keys is empty
// Create a shallow copy of `keys`. Mutating the `object` parameter
// is intended, mutating the `keys` parameter is not.
keys = Array.from(keys);
const lastKey = keys.pop();
const lastNode = keys.reduce((node, key) => node[key], object);
lastNode[lastKey] = value;
}
var object_ = [
{
"name":"Akshay"
}
];
var object_keys = [0, 'other_data'];
setValue(object_, object_keys, {
"age": 20,
"Sex": "male",
});
console.log(object_);