Get Keys of JSON-Object in JavaScript

get keys of json-object in JavaScript

[What you have is just an object, not a "json-object". JSON is a textual notation. What you've quoted is JavaScript code using an array initializer and an object initializer (aka, "object literal syntax").]

If you can rely on having ECMAScript5 features available, you can use the Object.keys function to get an array of the keys (property names) in an object. All modern browsers have Object.keys (including IE9+).

Object.keys(jsonData).forEach(function(key) {
var value = jsonData[key];
// ...
});

The rest of this answer was written in 2011. In today's world, A) You don't need to polyfill this unless you need to support IE8 or earlier (!), and B) If you did, you wouldn't do it with a one-off you wrote yourself or grabbed from an SO answer (and probably shouldn't have in 2011, either). You'd use a curated polyfill, possibly from es5-shim or via a transpiler like Babel that can be configured to include polyfills (which may come from es5-shim).

Here's the rest of the answer from 2011:

Note that older browsers won't have it. If not, this is one of the ones you can supply yourself:

if (typeof Object.keys !== "function") {
(function() {
var hasOwn = Object.prototype.hasOwnProperty;
Object.keys = Object_keys;
function Object_keys(obj) {
var keys = [], name;
for (name in obj) {
if (hasOwn.call(obj, name)) {
keys.push(name);
}
}
return keys;
}
})();
}

That uses a for..in loop (more info here) to loop through all of the property names the object has, and uses Object.prototype.hasOwnProperty to check that the property is owned directly by the object rather than being inherited.

(I could have done it without the self-executing function, but I prefer my functions to have names, and to be compatible with IE you can't use named function expressions [well, not without great care]. So the self-executing function is there to avoid having the function declaration create a global symbol.)

How to get all key in JSON object (javascript)

var input = {"document":
{"people":[
{"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
{"name":["hermione granger"],"age":["18"],"gender":["Female"]},
]}
}

var keys = [];
for(var i = 0;i<input.document.people.length;i++)
{
Object.keys(input.document.people[i]).forEach(function(key){
if(keys.indexOf(key) == -1)
{
keys.push(key);
}
});
}
console.log(keys);

How to get Key and Value from JSON object in Javascript(Postman)

Finally this works for me!(In Postman Script)

var resdata = JSON.parse(responseBody);
console.log(resdata);

key = Object.keys(resdata.data.list[0]);
console.log(key);

value =Object.values(resdata.data.list[0]);
console.log(value);

Get JSON key name

So now the problem I am facing is that, what about if I want to alert
success. Is there a need way to get it ?

If your object is

var obj = {"success":"You are welcome"};

You can get the array of keys as

var keys = Object.keys(obj);

and then print it as

console.log( keys[ 0 ] ); //or console.log( keys.join(",") )

var obj = {"success":"You are welcome"};var keys = Object.keys(obj);console.log(keys[0]);

How to get keys from json object in javascript

for each data in the array (map)
you want the ingredient part (.ingredients),
extract the keys (Object.keys)
and flatten the array (.flat())

array.map(a => a.ingredients).map(a => Object.keys(a)).flat();

You may prefer loop style. the only difference is flattening occurs with ... operator.

var results = [];
for (let a of array) {
results.push(...Object.keys(a.ingredients))
}

Get key from JSON object

Use Object.keys method.

In your case:

// `a` is defined somewhere there
...
Object.keys(a); // an array of object keys - but only the first level
console.log(Object.keys(a)[0]); // should log `d86f003c-bf0a-4b08-9744-1081c78ece9d`

for further reference - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

How can I get the key value in a JSON object?

First off, you're not dealing with a "JSON object." You're dealing with a JavaScript object. JSON is a textual notation, but if your example code works ([0].amount), you've already deserialized that notation into a JavaScript object graph. (What you've quoted isn't valid JSON at all; in JSON, the keys must be in double quotes. What you've quoted is a JavaScript object literal, which is a superset of JSON.)

Here, length of this array is 2.

No, it's 3.

So, i need to get the name (like amount or job... totally four name) and also to count how many names are there?

If you're using an environment that has full ECMAScript5 support, you can use Object.keys (spec | MDN) to get the enumerable keys for one of the objects as an array. If not (or if you just want to loop through them rather than getting an array of them), you can use for..in:

var entry;
var name;
entry = array[0];
for (name in entry) {
// here, `name` will be "amount", "job", "month", then "year" (in no defined order)
}

Full working example:

(function() {    var array = [    {      amount: 12185,      job: "GAPA",      month: "JANUARY",      year: "2010"    },    {      amount: 147421,      job: "GAPA",      month: "MAY",      year: "2010"    },    {      amount: 2347,      job: "GAPA",      month: "AUGUST",      year: "2010"    }  ];    var entry;  var name;  var count;    entry = array[0];    display("Keys for entry 0:");  count = 0;  for (name in entry) {    display(name);    ++count;  }  display("Total enumerable keys: " + count);
// === Basic utility functions function display(msg) { var p = document.createElement('p'); p.innerHTML = msg; document.body.appendChild(p); } })();

How to extract all keys and values from json? using Javascript

You can use Object.entries with .flat:

const fixedJson = `{
"a": 99,
"b": "this, is, string",
"c": "hi:"
}`;

const obj = JSON.parse(fixedJson);

const result = Object.entries(obj).flat();

console.log(result);


Related Topics



Leave a reply



Submit