[英]How to access value from the object within an array?
How can I access Name's value and assign it to an variable?如何访问 Name 的值并将其分配给变量?
var arr = [
{Name: "Jason",
Title: "Student",
Image: "asdf",
Status: "Happy"}
];
Try this:尝试这个:
var [{Name: name}] = arr;
This uses ES6 destructuring assignment .这使用 ES6 解构赋值。
First, the outermost []
is a way of referring to an array on the right hand side (in this example, arr
).首先,最外面的
[]
是一种引用右侧数组的方式(在本例中为arr
)。 Things placed within these square brackets (here's there's only one) refer to the first, second, and succeeding values of that array.放在这些方括号内的东西(这里只有一个)指的是该数组的第一个、第二个和后续值。 So here, the
{Name: name}
portion refers to the first (0th) element of the array.所以在这里,
{Name: name}
部分指的是数组的第一个(第 0 个)元素。 In other words, it is equivalent to换句话说,它等价于
var {Name: name} = arr[0];
The inner {}
is a way of referring to objects and picking them apart.内部
{}
是一种引用对象并将它们分开的方式。 {Name: name}
says to find the Name
property of the object being picked apart. {Name: name}
表示要找到被拾取对象的Name
属性。 Then the : name
part says to rename it to name
.然后
: name
部分说将其重命名为name
。 Since all this is occurring in the context of a var
statement, the result is declare a new variable with the name name
and assign the value being picked out to it .由于所有这些都发生在
var
语句的上下文中,因此结果是声明一个名为name
的新变量,并将从中选出的值分配给它。
Here's the more detailed sequence:这是更详细的序列:
var // Start a variable declaration
[ // Pick apart an array on the RHS, starting with 1st element
{ // Pick apart an object
Name // Find the property named `Name` in that object
:name // Rename it; this is the variable that will be declared!
} // Done picking apart the object
] // Done picking apart the array
= arr; // Specify the thing to deconstruct
Access the element at index 0
of array using bracket notation, then access property name Name
of object using dot or bracket notation使用括号表示法访问数组索引
0
处的元素,然后使用点或括号表示法访问属性Name
对象的Name
var arr = [
{Name: "Jason",
Title: "Student",
Image: "asdf",
Status: "Happy"}
];
var name = arr[0].Name; // alternatively, `arr[0]["Name"]`
var arr = [
{Name: "Jason",
Title: "Student",
Image: "asdf",
Status: "Happy"}
];
var myname = arr[0]['Name'];
console.log(myname);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.