【问题标题】:Property access of object within an array using a variable in Javascript [duplicate]使用Javascript中的变量访问数组中对象的属性[重复]
【发布时间】:2017-06-09 09:52:06
【问题描述】:

我正在尝试访问数组中对象内的对象的属性。蛮满口的。问题是我想使用一个变量来做到这一点。如果我用代码解释它可能会更容易;

var array= [
  { id: 0, client: { id:0, clientName: "John" }},
  { id: 1, client: { id:1, clientName: "Tom" }}
]
console.log(array[0][client][clientName]); // Displays correctly

所以上面的代码使用括号符号按预期工作。但正如我之前所说,我需要像这个例子一样使用变量;

var array= [
  { id: 0, client: { id:0, clientName: "John" }},
  { id: 0, client: { id:0, clientName: "John" }}
]
var property = "client.clientName";
console.log(array[0][property]); // Does not work

我理解为什么这段代码不起作用,但实际上这更像是一个伪代码来解释我想要实现的目标!

【问题讨论】:

标签: javascript arrays


【解决方案1】:

您可以使用一个函数,该函数将字符串与属性名称分开并减少给定的对象。

function getValue(object, path) {
    return path.split('.').reduce(function (o, k) {
        return (o || {})[k];
    }, object);
}

var array = [{ id: 0, client: { id:0, clientName: "John" } }, { id: 1, client: { id:1, clientName: "Tom" } }],
    property = "client.clientName";

console.log(getValue(array[0], property));

【讨论】:

  • 来自问题:关键是我想使用变量来执行此操作 - 您没有使用变量,而是将值硬编码到源代码中。
  • @Quentin,哦,我错过了。
【解决方案2】:

您不能以这种方式获得它,而是拆分并获取嵌套属性。使用Array#reduce方法通过String#split方法拆分属性字符串得到嵌套属性。

// split the string and iterate over the result array
property.split('.').reduce(function(o, p) {
  // check object defined and return nested property value
  return o && o[p];
  // set initial value as the object where you need to fetch data
}, array[0])

var array = [{
  id: 0,
  client: {
    id: 0,
    clientName: "John"
  }
}, {
  id: 0,
  client: {
    id: 0,
    clientName: "John"
  }
}]

var property = "client.clientName";
console.log(
  property.split('.').reduce(function(o, p) {
    return o && o[p];
  }, array[0])
);

【讨论】:

  • 嘿!挺好的,留着以后用:D
  • 嘿兄弟,这正是我需要的,谢谢!
  • @OliverFurmage : 很高兴帮助你:)
【解决方案3】:

var array= [
  { id: 0, client: { id:0, clientName: "John" }},
  { id: 0, client: { id:0, clientName: "John" }}
]
var property = "client.clientName",
    getPropByString=function(data,val){
      val=val.split(/\./g);
      var dataApp=data;
      val.forEach(function(prop){
        dataApp=dataApp[prop];
      });
      return dataApp;
    };
console.log(getPropByString(array[0],property));

【讨论】:

    猜你喜欢
    • 2012-11-28
    • 2014-08-04
    • 2015-03-13
    • 2012-06-30
    • 2019-10-18
    • 2013-12-02
    • 2018-10-18
    • 2020-06-03
    • 2019-10-15
    相关资源
    最近更新 更多