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

前端 未结 4 971
暖寄归人
暖寄归人 2021-01-14 03:01

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 Javascr

4条回答
  •  迷失自我
    2021-01-14 03:14

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

提交回复
热议问题