从位置0 javascript的内部对象获取值[重复]
Posted
技术标签:
【中文标题】从位置0 javascript的内部对象获取值[重复]【英文标题】:get value from inner object of position 0 javascript [duplicate] 【发布时间】:2020-10-16 00:05:56 【问题描述】:我有一个对象集。我想获得位置 0 的值。例子。 men 在零位。我想访问 label 和 innerlabel 里面的选项。
const obj1 =
men:
value: "men",
attribute_label: "Men",
type: "select",
options:
1: innerlabel: "infant", value_string: "1" ,
2: innerlabel: "baby", value_string: "2"
,
women:
value: "women",
attribute_label: "Women",
type: "select",
options:
1: innerlabel: "infant", value_string: "1" ,
2: innerlabel: "baby", value_string: "2"
,
kids:
value: "kids",
attribute_label: "Kids",
type: "select",
options:
7: innerlabel: "infant", value_string: "1" ,
8: innerlabel: "baby", value_string: "2"
;
【问题讨论】:
所以你想返回 set1 中的 men 对象?fisrtValue = Object.values(set1)[0]
对象中没有位置0。我的意思是,您可以使用Object.keys(obj1)[0]
和其他静态方法,但不能保证它会是men
。对象不应该用作有序集合
好的。所以无论如何我都可以订购吗? @adiga
【参考方案1】:
你可以拿Object.values()
的对象,得到它的第一个位置:
var set1 =
men: value: "men", label: "Men", type: "select", "options": [ innerlabel: "boy", value_string: "1", label: "Guy", value_string: "2"] ,
women: value: "women", label: "Women", type: "select", "options": [ innerlabel: "lady", value_string: "1" , label: "girl", value_string: "2"] ,
kids: value: "kids", label: "Kids", type: "select" ,"options": [ innerlabel: "infant", value_string: "1" , innerlabel: "baby", value_string: "2"] ,
;
const [firstValue] = Object.values(set1);
console.log(firstValue);
【讨论】:
我想拿到标签。和 innerLabel 里面的选项@gorak【参考方案2】:const getObjAt = (data, pos) =>
return Object.values(data)[pos];
;
const obj1 =
men:
value: 'men',
attribute_label: 'Men',
type: 'select',
options:
1: innerlabel: 'Men', value_string: '1' ,
2: innerlabel: 'Boy', value_string: '2' ,
,
,
women:
value: 'women',
attribute_label: 'Women',
type: 'select',
options:
1: innerlabel: 'women', value_string: '1' ,
2: innerlabel: 'lady', value_string: '2' ,
,
,
kids:
value: 'kids',
attribute_label: 'Kids',
type: 'select',
options:
7: innerlabel: 'infant', value_string: '1' ,
8: innerlabel: 'baby', value_string: '2' ,
,
,
;
const objAt_0 = getObjAt(obj1, 0);
console.log(objAt_0.attribute_label);
Object.values(objAt_0.options).map(option => console.log(option.innerlabel));
const objAt_1 = getObjAt(obj1, 1);
console.log(objAt_1.attribute_label);
Object.values(objAt_1.options).map(option => console.log(option.innerlabel));
【讨论】:
我想要两个innerLabels @Nithish Gandesiri 已更新代码以打印所有innerlabel
s。请检查
其打印未定义@Nithish Gandesiri
我认为问题中提供的初始数据和当前数据有一些变化,我已经根据更新的问题更新了答案。请立即检查。以上是关于从位置0 javascript的内部对象获取值[重复]的主要内容,如果未能解决你的问题,请参考以下文章