首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何仅获取第一个对象值键值

如何仅获取第一个对象值键值
EN

Stack Overflow用户
提问于 2019-03-02 05:47:56
回答 5查看 94关注 0票数 -8

我有一个对象数组,比如-

array = [{label:"1",value:"11"},
         {label:"2",value:"22"},
         {label:"3",value:"33"},
         {label:"4",value:"44"},
        ];

如何获取第一个对象(11)的value

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2019-03-02 05:49:54

只需使用array[0].value即可

var array = [{
    label: "1",
    value: "11"
  },
  {
    label: "2",
    value: "22"
  },
  {
    label: "3",
    value: "33"
  },
  {
    label: "4",
    value: "44"
  },
];

var firstValue = array[0].value;
console.log(firstValue);

您也可以像这样使用解构:

var array = [{
    label: "1",
    value: "11"
  },
  {
    label: "2",
    value: "22"
  },
  {
    label: "3",
    value: "33"
  },
  {
    label: "4",
    value: "44"
  },
];

var [{ value: firstValue }] = array;
console.log(firstValue);

票数 2
EN

Stack Overflow用户

发布于 2019-03-02 05:54:44

您可以通过获取带有键0(仅是数组的第一个元素)的对象,然后获取value属性来获取一个时髦的destructuring

var array = [{ label: "1", value: "11" }, { label: "2", value: "22" }, { label: "3", value: "33" }, { label: "4", value: "44" }],
    { 0: { value } } = array;
    
console.log(value);

票数 1
EN

Stack Overflow用户

发布于 2019-03-02 05:50:40

只需获取array0索引中的项。有关更多详细信息,请参阅评论:

//The initial data
var array = [{
    label: "1",
    value: "11"
  },
  {
    label: "2",
    value: "22"
  },
  {
    label: "3",
    value: "33"
  },
  {
    label: "4",
    value: "44"
  },
];

//Access the item you want by it's index in the array (0-based)
var firstItem = array[0];

//Grab the "value" property from the object
var value = firstItem.value;

//Log your value
console.log(value);

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54952746

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档