Javascript 通过字符串从对象和子对象数组中获取动态值

Javascript 通过字符串从对象和子对象数组中获取动态值,javascript,arrays,object,Javascript,Arrays,Object,我想知道是否有一种方法可以使用字符串动态获取子对象: 例:行业描述 var fields = [{ id: "1", industry: { description: "Test Industry1" } }, { id: "2", industry: { description: "Test Industry2" } } ]; var field1 = "id"; var field2 = "in

我想知道是否有一种方法可以使用字符串动态获取子对象:

例:行业描述

var fields = [{
    id: "1",
    industry: {
      description: "Test Industry1"
    }
  },
  {
    id: "2",
    industry: {
      description: "Test Industry2"
    }
  }
  ];

  var field1 = "id";
  var field2 = "industry.description";

  var val1 = fields[0][field1];
  var val2 = fields[0][field2]; // How can I get 'Test Industry1' here?

  console.log(val1);
  console.log(val2);
industry.description密钥将不起作用。 您需要的是首先获取行业密钥下的对象,然后从中获取描述。 像这样:

字段[0][行业][说明]//测试行业1 industry.description密钥将不起作用。 您需要的是首先获取行业密钥下的对象,然后从中获取描述。 像这样:

字段[0][行业][说明]//测试行业1 或者:

fields[0]["industry"]["description"];
或者将其分为多个字段,例如[field2][field3],其中field2=行业,field3=说明

或者,使用reduce处理当前字符串:

var val2 = field2.split(".").reduce((o, k) => o[k], fields[0]);
或者:

fields[0]["industry"]["description"];
或者将其分为多个字段,例如[field2][field3],其中field2=行业,field3=说明

或者,使用reduce处理当前字符串:

var val2 = field2.split(".").reduce((o, k) => o[k], fields[0]);

允许通过动态提供的路径从对象中提取嵌套值的简单解决方案是:

function getValue(object, path) {

  // Break input path into parts separated by '.' via split
  const parts = path.split(".");

  // Iterate the parts of the path, and reduce that parts array to a single
  // value that we incrementally search for by current key, from a prior
  // nested "value"
  return parts.reduce((value, key) => value ? value[key] : value, object)  
}

console.log(getValue(fields[0], "industry.description")); // Test Industry1
这样做的好处是它很简单,不需要向项目中添加其他库。以下是它在代码上下文中的工作方式:

函数getValueobject,路径{ 常量部分=路径分割。; return parts.reducevalue,key=>value?value[key]:value,object } 变量字段=[{ id:1, 行业:{ 描述:测试行业1 } }, { id:2, 行业:{ 描述:测试行业2 } } ]; var field1=id; var field2=行业说明; console.loggetValuefields[0],field1
console.loggetValuefields[0],field2允许通过动态提供的路径从对象中提取嵌套值的简单解决方案是:

function getValue(object, path) {

  // Break input path into parts separated by '.' via split
  const parts = path.split(".");

  // Iterate the parts of the path, and reduce that parts array to a single
  // value that we incrementally search for by current key, from a prior
  // nested "value"
  return parts.reduce((value, key) => value ? value[key] : value, object)  
}

console.log(getValue(fields[0], "industry.description")); // Test Industry1
这样做的好处是它很简单,不需要向项目中添加其他库。以下是它在代码上下文中的工作方式:

函数getValueobject,路径{ 常量部分=路径分割。; return parts.reducevalue,key=>value?value[key]:value,object } 变量字段=[{ id:1, 行业:{ 描述:测试行业1 } }, { id:2, 行业:{ 描述:测试行业2 } } ]; var field1=id; var field2=行业说明; console.loggetValuefields[0],field1 console.loggetValuefields[0],field2