简体   繁体   中英

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)

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);

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"]

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(' ');
}

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);

If you pass a function to JSON.parse , it will be called each time a value is parsed:

function get_values(json) {
   let values = []
   JSON.parse(json, (key,value)=>{ values.push(value) })
   return values
}

ex:

get_values(`{"a":1, "b":[true, false], "c":3}`)
// returns a list of:
• 1
• true
• false
• [true, false]
• 3
• {a:1, b:[true, false], c:3}

Note: If you don't consider the full object to be a "value", just remove the last item.

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