Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract only values from JSON object in javascript without using a loop

is there a "Nice" way to get all the values out of a json object (I don't care about the keys) - just get the values into array, without using a loop ? (lang is Javascript)

like image 302
Dani Avatar asked Dec 19 '16 11:12

Dani


4 Answers

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);
like image 50
Quentin Avatar answered Oct 06 '22 23:10

Quentin


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"]
like image 20
Lukas Skirkevičius Avatar answered Oct 06 '22 23:10

Lukas Skirkevičius


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.

function textFromJson(json) {
    if (json === null || json === undefined) {
      return '';
    }
    if (!Array.isArray(json) && !Object.getPrototypeOf(json).isPrototypeOf(Object)) {
      return '' + json;
    }
    const obj = {};
    for (const key of Object.keys(json)) {
        obj[key] = textFromJson(json[key]);
    }
    return Object.values(obj).join(' ');
}
like image 24
King Friday Avatar answered Oct 06 '22 21:10

King Friday


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);
like image 26
Ramon-san Avatar answered Oct 06 '22 23:10

Ramon-san