简体   繁体   English

如果对象键在打字稿中是动态的,如何获取值?

[英]how to get value if the object key is dynamic in typescript?

I have an array of object.structure is like that. 我有一个object.structure数组就是这样。

animal = [{"cow":{"leg":4,"eye":2}},{"monkey":{"leg":2,"eye":2}}]

here first key is dynamic like cow and monkey 这里的第一个关键是动态像牛和猴子

so my question is how can i access the key leg if first key is dynamic 所以我的问题是如果第一个键是动态的,我如何访问关键段

If you are sure that each object within the array as only 1 property (which would be the type of animal), you can do something like this. 如果你确定数组中的每个对象只有1个属性(这将是动物的类型),你可以做这样的事情。

 animals = [{"cow":{"leg":4,"eye":2}},{"monkey":{"leg":2,"eye":2}}]; for (let animal of animals) { let propName = Object.keys(animal)[0]; let result = animal[propName]; console.log(result); // <- Do what you want with it } 

这将为您提供一系列具有每只动物内容的对象。

animals.map(animal => animal[Object.keys(animal)[0]]);

Maybe convert it into a "non-dynamic-key" object? 也许将其转换为“非动态密钥”对象?

 const animal = [{"cow":{"leg":4,"eye":2}},{"monkey":{"leg":2,"eye":2}}] const newanimal = animal.map(obj => { const keys = Object.keys(obj) return keys.map(key => ({ key, value: obj[key] })) }).flat(Math.Infinity) console.log(newanimal) 

1) Find an animal with that key 1)找到具有该密钥的动物

2) Return it with [animal] 2)用[动物]归还

3) Use it as you would ( .leg ) 3)像你一样使用它( .leg

const animals = [{ cow: { leg: 4, eye: 2 } }, { monkey: { leg: 2, eye: 2 } }];

const animal = 'cow';
const leg = animals.find(a => !!a[animal])[animal].leg;

You can use map & Object.keys . 您可以使用mapObject.keys map will return a new array. map将返回一个新数组。 Object.keys is use to get all the keys inside each of the object in animal array.Then this line elem[getKeys].leg will retrieve the value of the leg key Object.keys用于获取动物数组中每个对象内的所有键。然后这行elem[getKeys].leg将检索leg键的值

 let animal = [{ "cow": { "leg": 4, "eye": 2 } }, { "monkey": { "leg": 2, "eye": 2 } }]; let legVal = animal.map((elem) => { let getKeys = Object.keys(elem)[0]; return elem[getKeys].leg }) console.log(legVal) 

You can use the newly added Object.entries , which make the most sense imo. 您可以使用新添加的Object.entries ,它们是最有意义的imo。

Thus for your data you have: 因此,对于您的数据,您有:

const animal = ...
for (a of animal) {
    const [animalName, animalDesc] = Object.entries(a)[0]; // assumes there is only one
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM