简体   繁体   中英

Stringify An Object Key's Name

I've tried JSON.stringify() and Object.Keys() however they're not working for me, they do not output the Object Key's Name

My .JSON File:

{
  "KittenLauncher": {
    "a": "value1",
    "b": "value2"
  }
}

My Current JS File:

const obj = require('../../someJSONFileIHave.json');
let rname = "Kitten";
let rating;

function getValueByPartialKey(obj, key) {

    try {
        rating = 'A, B, C';
        return (Object.entries(obj).find(([k, v]) => k.includes(key)))[1]; // Returns KittenLauncher as an [Object]
    } catch (e) {
        console.log("Object Key does not exist!")
    }

}

return console.log(JSON.stringify(getValueByPartialKey(obj, rName))); // Outputs "{"a": "value1","b": "value2"}"

I'd like it to output the Object Key's name as such: "KittenLauncher"

Is there a correct way to do this?

In your .js file, you already have,

const obj = require('../../someJSONFileIHave.json');

And your JSON file is,

{
  "KittenLauncher": {
    "a": "value1",
    "b": "value2"
  }
}

So, to get KittenLauncher as output, you can use,

const output = Object.keys(obj)[0]  `//Output is KittenLauncher`

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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