我想快速分配如下:
obj = {};
obj["train-11456"]["2016-12-11" ]["chair car"] = 'waitlisted';
所有这些元素都是对象。
我们可以在PHP中执行此操作,并自动创建它们。
这样分配的最简单方法是什么?
更长的方法是:
obj["train-11456"] = {} //only if this key does not already exist
obj["train-11456"]["2016-12-11" ] = {}; //only if this key does not alreadu exist
obj["train-11456"]["2016-12-11" ]["chair car"] = 'waitlisted';
答案 0 :(得分:3)
你可以这样做
obj = {
"train-11456": {
"2016-12-11": {
"chair car" : "waitlisted"
}
}
};
OR
obj = {"train-11456":{"2016-12-11":{"chair car":"waitlisted"}}};
答案 1 :(得分:2)
没有直接的方法可以做到这一点。但是你可以编写一个实用程序函数来为你完成它。它的简写
function objUtil (obj) {
var _o = obj || {};
return function () {
var args = [].slice.call(arguments, 0),
val = args.splice(args.length - 1, 1)[0],
res = {},
index, length, key, objPointer, lastObjPtr;
objPointer = _o;
for (index = 0, length = args.length; index < length; index ++) {
key = args[index];
lastObjPtr = objPointer;
objPointer = objPointer[key] = {};
}
lastObjPtr[key] = val;
return _o;
}
}
然后将其称为
var obj,
populateObj = objUtil(obj={});
populateObj('train-11456', '2016-12-11', 'chair car', 'waitlisted');
console.log(obj);