Extract Only Values From Json Object In Javascript Without Using A Loop
Solution 1:
It depends on how you define "loop".
You can extract the properties with Object.keys
and then map
them to their values.
… it's still essentially a loop under the hood though.
var json = `{ "foo": 1, "bar": 2, "baz": 3 }`;
var obj = JSON.parse(json);
var values = Object.keys(obj).map(function (key) { return obj[key]; });
console.log(values);
With weaker browser support you could use the values
method.
var json = `{ "foo": 1, "bar": 2, "baz": 3 }`;
var obj = JSON.parse(json);
var values = Object.values(obj);
console.log(values);
Solution 2:
I think you are looking for Object.values() function, just pass the object to the values method of Object as first param. That's it!
Object.values({something: 'lol'});
> ["lol"]
Solution 3:
Recursively extract as text
Yes, this is a loop but the underlying methods you are calling such as Object.values
or arr.map
are still loops. I found this useful for extracting text out of a json object for full text search in particular and thought it useful as I came here initially needing this but the answers only touched the surface as json is recursive in nature.
functiontextFromJson(json) {
if (json === null || json === undefined) {
return'';
}
if (!Array.isArray(json) && !Object.getPrototypeOf(json).isPrototypeOf(Object)) {
return'' + json;
}
const obj = {};
for (const key ofObject.keys(json)) {
obj[key] = textFromJson(json[key]);
}
returnObject.values(obj).join(' ');
}
Solution 4:
With ES2017 you have Object.values(). You can polyfill it also.
Only you need is transform JSON to JavaScript object and call Object.values(). The result is an array of values.
var obj = JSON.parse(jsonData);
var result = Object.values(obj);
Post a Comment for "Extract Only Values From Json Object In Javascript Without Using A Loop"