I try to set a value into nested array by a key.
My Object looks like
var Obj = {
key1: {
key2: value,
}
}
I try to set key1 by key1.key2
like
const name = `key1.key2`
Obj[name] = value
I knew I need to do it like Obj['key1']['key2']
but I get only a string
which looks like key1.key2
I try to set a value into nested array by a key.
My Object looks like
var Obj = {
key1: {
key2: value,
}
}
I try to set key1 by key1.key2
like
const name = `key1.key2`
Obj[name] = value
I knew I need to do it like Obj['key1']['key2']
but I get only a string
which looks like key1.key2
-
Is it
key1
andkey2
, orkey
andkey1
? – Willis Blackburn Commented Dec 21, 2019 at 20:26 -
Sorry I fixed. It is
key1
andkey2
. @WillisBlackburn – Antoni Commented Dec 21, 2019 at 20:28 - Are you open to / able to use a library here? There are a number of toolbelt libraries that will make this operation ridiculously easy (Ramda, lodash). – tex Commented Dec 21, 2019 at 20:45
- @tex Yes I can also use a library – Antoni Commented Dec 21, 2019 at 20:46
4 Answers
Reset to default 8If you don't mind using a library, Ramda and lodash offer helper functions that make this sort of operation very simple
With Ramda (slightly more verbose than lodash for this specific operation, but I prefer Ramda to lodash):
const Obj = {
key1: {
key2: 1,
}
}
const name = `key1.key2`
console.log(
R.assocPath(name.split('.'), 2, Obj)
)
// --> { key1: { key2: 2 } }
<script src="https://cdnjs.cloudflare./ajax/libs/ramda/0.26.1/ramda.min.js"></script>
With lodash:
const Obj = {
key1: {
key2: 1,
}
}
const name = `key1.key2`
console.log(
_.set(Obj, name, 2)
)
// --> { key1: { key2: 2 } }
<script src="https://cdnjs.cloudflare./ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
You could do it like so:
function getVal(obj, key, val) {
const keys = key.split('.');
let pre = obj;
for(let i = 0; i < keys.length - 1; i++) {
pre = pre[keys[i]];
}
pre[keys.length] = val;
return pre;
}
console.log(getVal({key1: {key2: 1}}, 'key1.key2', 2));
Update: I think I now understand that you have a string with the value 'key1.key2'
and you want to use that to index Obj
.
If that's what you want to do, first split the string into a list of keys, then evaluate each in series.
let keys = key.split('.')
let answer = keys.reduce((a, k) => a[k], Obj)
Update 2: If you want to set, then what you want to is find the object identified by the second-to-last key in your string, then use the last key to set value on that object.
let keys = key.split('.')
let target = keys.slice(0, keys.length - 1).reduce((a, k) => a[k], Obj)
target[keys[keys.length -1]] = value
Previous answer: I'm not 100% sure what you're trying to do here, so let's take it step by step.
First, the easy part. If you have some object Obj
, then indexing it with a key gets or sets the value for that key. So this:
let Obj = {}
Obj['key1.key2'] = value
produces an object that looks like this:
{
key1.key2: value
}
That's not what you want. You want an object that has one key, key1
, and you want the value of that key to be another object with a key key2
, and you want the value of key2
to be value
.
let Obj = {} // an object...
Obj['key1'] = {} // that has key1, which is an object...
Obj['key1']['key2'] = value // that has key2, which is value
To retrieve the value just use the same syntax as in the second line.
Obj['key1']['key2']
The key point (bad pun, sorry) is that there are two objects involved; one is Obj
and the other is Obj['key1']
.
Try this out:
function setValue(obj, keyString, value){
var keys = keyString.split(".");
var tempObj = Obj;
for(var i = 0; i < keys.length; i++){
if(i == keys.length - 1){
tempObj[keys[i]] = value;
return true;
}
if(!(keys[i] in tempObj)) return false;
tempObj = tempObj[keys[i]];
}
}
var Obj = {
key1: {
key2: "value",
}
}
if(setValue(Obj, "key1.key2", "new value")){
console.log(Obj);
}
The setValue function recognizes when an invalid keyString is provided and returns false if that's the case so you don't run into any trouble. If iverything goes smoothly, it returns true.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744401582a4572414.html
评论列表(0条)