Javascript Javascript从数组内的对象中获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34507674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:27:55  来源:igfitidea点击:

Javascript get value from an object inside an array

javascriptarraysobject

提问by leox

I have an object with key value pairs inside an array:

我在数组中有一个键值对的对象:

var data = [
  {
  "errorCode":100,
  "message":{},
  "name":"InternetGatewayDevice.LANDevice.1.Hosts.HostNumberOfEntries",
  "value":"2"
  }
];

I want to get the value of "value" key in the object. ie, the output should be "2".

我想获取对象中“value”键的值。即,输出应为“2”。

I tried this:

我试过这个:

console.log(data[value]);
console.log(data.value);

Both logging "undefined". I saw similar questions in SO itself. But, I couldn't figure out a solution for my problem.

两者都记录“未定义”。我在 SO 本身中看到了类似的问题。但是,我无法为我的问题找到解决方案。

采纳答案by Abhijith Sasikumar

You are trying to get the value from the first element of the array. ie, data[0]. This will work:

您正在尝试从数组的第一个元素中获取值。即,data[0]。这将起作用:

console.log(data[0].Value);

回答by leox

You can use the mapproperty of the array. Never try to get the value by hardcoding the index value, as mentioned in the above answers, Which might get you in trouble. For your case the below code will works.

您可以使用数组的map属性。切勿尝试通过硬编码索引值来获取值,如上述答案中所述,这可能会给您带来麻烦。对于您的情况,以下代码将起作用。

data.map(x => x.Value)

回答by Alexander T.

datais Arrayyou need get first element in Arrayand then get Valueproperty from Object,

dataArray你需要得到第一个元素Array,然后得到Value物业Object

var data = [{
  "ErrorCode":100,
  "Message":{},
  "Name":"InternetGatewayDevice.LANDevice.1.Hosts.HostNumberOfEntries",
  "Value":"2"
}];

console.log(data[0].Value);

回答by Anand Singh

Try this... Actually Here Datais an array of object so you first need to access that object and then you can access Valueof that object.

试试这个...实际上这Data是一个对象数组,所以您首先需要访问该对象,然后才能访问Value该对象。

var data = [
  {
  "ErrorCode":100,
  "Message":{},
  "Name":"InternetGatewayDevice.LANDevice.1.Hosts.HostNumberOfEntries",
  "Value":"2"
  }
];

alert(data[0].Value);

回答by ashish1dev

what you are trying to read is an object which an element of an array, so you should first fetch the element of array by specifying its index like data[0] and then read a property of the fetched object, i.e. .value,

您要读取的是一个对象,它是数组的元素,因此您应该首先通过指定其索引(如 data[0])来获取数组的元素,然后读取所获取对象的属性,即 .value,

so the complete syntax would be data[0].value Hope it helps !

所以完整的语法是 data[0].value 希望它有帮助!