我有一个存储在字符串
中的变量 var employee = {
name: 'person',
job: {
post: 'developer',
since: 2010,
desk: {
number: '1',
}
}
};
如何从字符串中获取钥匙串值,例如
var variable = "job.desk.number";
console.log(variable);
//this should return 1
更新3 !!
@ T.J。克劳德的答案实际上是最好的答案。
他的功能快速而整洁。 :) horry!
答案 0 :(得分:2)
拆分字符串,使你有一个键数组,然后遍历它们从对象轮流获取每个键,记住你从对象得到的最后一件事:
var value = variable.split('.').reduce(function(prev, key) {
return prev[key];
}, employee);
snippet.log(value);
示例:
var employee = {
name: 'person',
job: {
post: 'developer',
since: 2010,
desk: {
number: '1',
}
}
};
var variable = "job.desk.number";
var value = variable.split('.').reduce(function(prev, key) {
return prev[key];
}, employee);
snippet.log(value);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
请注意Array#reduce
是ES5的东西,因此它适用于所有现代浏览器,但不适用于旧版浏览器。不过,它可以是填充/填充的。或者,如果您只是想使用for
循环:
var keys = variable.split('.');
var value = employee;
var index;
for (index = 0; index < keys.length; ++index) {
value = value[keys[index]];
}
snippet.log(value);
示例:
var employee = {
name: 'person',
job: {
post: 'developer',
since: 2010,
desk: {
number: '1',
}
}
};
var variable = "job.desk.number";
var keys = variable.split('.');
var value = employee;
var index;
for (index = 0; index < keys.length; ++index) {
value = value[keys[index]];
}
snippet.log(value);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
答案 1 :(得分:0)
让我们说例如你的变量emplyee就像
var employee = "{ name: 'person', job: { post: 'developer', since: 2010, desk: { number: '1', } } }";
实际上是一个字符串,然后您需要使用JSON.parse(employee)
您可以像
一样访问您的变量var variable = employee.job.desk.number
您的案例的替代方案是:
var variable = "" + employee.job.desk.number;
答案 2 :(得分:0)
结果实际上是有效的,但我对性能感到疑惑。
var _getKeyChainValueFromObject = function (keychain, root) {
var items = [];
if (keychain.indexOf(".") > 0)
items = keychain.split(".");
else
return root[keychain];
for (var i = 0; i < items.length ; i++) {
for (var property in root) {
var key = items[i];
if (property === key) {
if (typeof (root[property]) === "object") {
var scope = root[property];
items.splice(0, 1);
//get the resource recursively
return _getKeyChainValueFromObject(items.join('.'), scope);
}
}
}
}
};