Get the value of an object with an unknown single key in JS

前端 未结 2 778
我在风中等你
我在风中等你 2020-11-30 11:11

How can I get the value of an object with an unknown single key?

Example:

var obj = {dbm: -45}

I want to get the -45 value without

2条回答
  •  我在风中等你
    2020-11-30 12:07

    There's a new option now: Object.values. So if you know the object will have just one property:

    const array = Object.values(obj)[0];
    

    Live Example:

    const json = '{"EXAMPLE": [ "example1","example2","example3","example4" ]}';
    const obj = JSON.parse(json);
    const array = Object.values(obj)[0];
    console.log(array);

    If you need to know the name of the property as well, there's Object.entries and destructuring:

    const [name, array] = Object.entries(obj)[0];
    

    Live Example:

    const json = '{"EXAMPLE": [ "example1","example2","example3","example4" ]}';
    const obj = JSON.parse(json);
    const [name, array] = Object.entries(obj)[0];
    console.log(name);
    console.log(array);

提交回复
热议问题