简体   繁体   English

使用Lodash`_.get`使用括号表示法访问对象键

[英]Using Lodash `_.get` to access object key using bracket notation

I have the following 我有以下内容

const key = 'foo';
const test = { foo: { bar: 23 } };

and I'd like to use lodash get to access the value of test[key].bar . 我想使用lodash get来访问test[key].bar的值。

I want to use the bracket notation on the first indicator... 我想在第一个指标上使用括号表示法......

_.get(test, '[key].bar'); // results in undefined

Surely there's a way... 当然有办法......

You need to put the value of key into your path string: 您需要将key放入路径字符串中:

_.get(test, key + '.bar');

In ES2015 you can use a template literal (interpolated string): 在ES2015中,您可以使用模板文字 (插值字符串):

_.get(test, `${key}.bar`);

You can pass an array to define the evaluation path. 您可以传递数组以定义评估路径。

This is one pretty clean solution to your problem: 这是一个非常干净的解决方案:

 const test = {foo: {bar: 23}} const key = 'foo' console.log(_.get(test, [key, 'bar'])) // 23 
 <script src='https://cdn.jsdelivr.net/lodash/4.16.6/lodash.min.js'></script> 

const test = { foo: { bar: 23 } };
const key = 'foo';
const search = key + '.bar';

const result = _get(test, search);

This is a proposal which uses a global variable, when enclosed in brackets. 这是一个使用全局变量的提案,当括在括号中时。

 function getValue(object, path) { return path.replace(/(?=\\[)/g, '.').split('.').reduce(function (o, k) { var m = k.match(/^\\[([^\\]]*)\\]$/); return m ? (o || {})[window[m[1]]] : (o || {})[k]; }, object); } var test = { foo: { bar: 23 } }, key = 'bar'; console.log(getValue(test, 'foo[key]')); 

Parse JSON before get JSON.parse(<YOUR JSON String or Obj>) 在获取JSON.parse(<YOUR JSON String or Obj>)之前解析JSON

const test = { foo: { bar: 23 } };
const key = 'foo';


const result = _get(JSON.parse(test), key );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用括号符号(带有变量)访问对象属性的好处 - Benefit of using bracket notation (with variables) to access a property of an object 使用带有变量的括号表示法来访问 object 属性返回未定义 - Using bracket notation with a variable to access object property returns undefined 使用方括号符号访问多个字符? - Access multiple characters using bracket notation? 实现一个函数来访问对象的属性,而不是使用点符号或方括号符号来访问属性? - Implementing a function to access an object's property versus accessing the property using dot notation, or bracket notation? 使用括号符号访问对象中的属性 - Accessing Properties in object using bracket notation 使用括号表示法在对象内调用函数 - Calling function inside object using bracket notation javascript中使用方括号表示法的嵌套对象 - Nested object using square bracket notation in javascript 使用功能和括号符号将属性添加到对象 - Adding properties to an object using function and bracket notation 在 JavaScript 中,是否有任何方法可以在不使用点符号或括号符号的情况下获取 object 的属性? - In JavaScript, do there exist any ways to get a property of an object without using dot notation or bracket notation? 使用方括号表示法访问具有“n”级深度对象的嵌套对象 - access nested object with "n" level deep object using square bracket notation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM