Key-based iterative function for intercepting values

Looking to extract values associated with the key text from a large JSON file. Here is an example snippet:

    type":"doc",
   "content":[
      {
         "type":"paragraph",
         "content":[
            {
               "text":"this is a simple page, about a simple umbrella.",
               "type":"text"
            }
         ]
      },
      {
         "type":"paragraph",
         "content":[
            {
               "text":"you can use this text to find the umbrella page.",
               "type":"text"
            }
         ]
      },
      {
         "type":"paragraph",
         "content":[
            {
               "text":"do you like it?",
               "type":"text"
            }
         ]
      },

To achieve this without recursion, I am exploring the use of an iterative function instead of Object.keys. Previous attempts with JSON.stringify yielded poor performance:

const obj = JSON.parse(content);
let ret = '';
JSON.stringify(obj, (_, nested) => {
  if (nested && nested[key]) {
    ret += nested[key] + '\n';
  }
  return nested;
});

Answer №1

If you're aiming to extract the main text, try utilizing this handy approach.

var reg = /(?<=\")\w+(?=\"\:)/g
var jsonValue = '{"glossary": {"title": "example glossary","GlossDiv": {"title": "S","GlossList": {"GlossEntry": {"ID": "SGML","SortAs": "SGML","GlossTerm": "Standard Generalized Markup Language","Acronym": "SGML","Abbrev": "ISO 8879:1986","GlossDef": {"para": "A meta-markup language, used to create markup languages such as DocBook.","GlossSeeAlso": ["GML", "XML"]},"GlossSee": "markup"}}}}}';

console.log(jsonValue.match(reg));

Answer №2

Not quite sure if I understand the question, but here is a solution using lodash:

const _ = require('lodash');
    
const data = '{"type":"doc","content":[{"type":"paragraph","content":[{"text":"this is a simple page, about a simple umbrella.","type":"text"}]},{"type":"paragraph","content":[{"text":"you can use this text to find the umbrella page.","type":"text"}]},{"type":"paragraph","content":[{"text":"do you like it?","type":"text"}]}]}';

const obj = JSON.parse(data);

const getText = (obj) => {
  const result = Object.entries(obj).reduce((acc, [key, value]) => {
    if (key === 'text') acc.push(value);
    if (_.isObject(value)) acc.push(...getText(value));
    if (_.isArray(value)) value.map((item) => getText(item));
    return acc;
  }, []);

  return result;
}

console.log(getText(obj));
// [
//   'this is a simple page, about a simple umbrella.',
//   'you can use this text to find the umbrella page.',
//   'do you like it?'
// ]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to retrieve the final directory name on Windows using cmd?

I am currently working on setting up a custom Sublime Text Build system for Windows, where I need to extract the last folder name. The standard variables available do not provide me with the desired result, so I have been using $folder which gives me the ...

What is the method for submitting a POST request with a JSON body that consists of only a string, without any key-value pairs included?

There was a developer who, not knowing the correct JSON format for key-value pairs, created a JSON body that looks like this: { "dog" } Instead of { "dog": "dog" } I must send the request from a JavaScript file, and the body needs to be in JSON f ...

What could be causing the ng-if function to continuously loop?

I have encountered an issue where I am passing a boolean function in the ngIf attribute instead of a boolean condition in my HTML template file. This boolean function seems to be repeating itself depending on the amount of data present in the variable &apo ...

The Angular router seems to be refusing to show my component

My Angular 2 App includes a Module called InformationPagesModule that contains two lazy load components (Info1 Component and Info2 Component). I would like these components to load when accessing the following routes in the browser: http://localhost:4200/ ...

Developing an attribute in a constructor using Typescript

My javascript code is functioning perfectly: class myController { constructor () { this.language = 'english' } } However, I encountered an issue when trying to replicate the same in Typescript export default class myController { co ...

The absence of the function crypto.createPrivateKey is causing issues in a next.js application

For my next.js application, I am utilizing the createPrivateKey function from the crypto module in node.js. However, I encountered an issue as discussed in this thread: TypeError: crypto.createPrivateKey is not a function. It seems that this function was a ...

The absence of a function implementation right after the declaration within a TypeScript class is a common issue that needs

I received a handwritten array to populate a table for my class, however I am now fetching this array's content from a JSON during the ngOnInit phase and it is not structured in the way I require. Therefore, I am attempting to create a function that ...

Adjust color in real-time with JavaScript

I am using a json file to store data for generating a diagram, and I want to change the color of the diagram conditionally based on an attribute in the json. If the attribute is false, the color should be red, and if true, it should be green. Here is a sni ...

How to trigger a function in a separate component (Comp2) from the HTML of Comp1 using Angular 2

--- Component 1--------------- <div> <li><a href="#" (click)="getFactsCount()"> Instance 2 </a></li> However, the getFactsCount() function is located in another component. I am considering utilizing @output/emitter or some o ...

Oh no, an issue has occurred with The Angular Compiler! It appears that TypeScript version 3.9.10 was found instead of the required version, which should be >=3.6.4 and <

After upgrading my angular application from version 5 to version 9, I encountered an issue while trying to deploy my code on the server. ERROR in The Angular Compiler requires TypeScript >=3.6.4 and <3.9.0 but 3.9.10 was found instead. Even though ...

Local environment successfully executes API calls, but encounters issues in live environment

My custom-built API in PHP involves a simple GET request to a MariaDB database, fetching records in JSON format. The folder structure is as follows: /api /api/some/read.php /api/some/read2.php /config /config/Database.php /models /models/call.php /models ...

Tips for bringing in an enum from TypeScript?

I am working with a module defined in TypeScript that looks like this: declare module MyTypes { export enum MyEnum { GOOD = 'Good', BAD = 'Bad', UNKNOWN = '-' } export interface MyType1 { ...

What is the best way to iterate through a JSON object using the stages array provided?

I am facing an issue with parsing the provided json to display the desired output on the screen. These are the steps I need to follow for parsing this json: 1. Extract the stages array from the json - for example, stages ["check_dependency_progress", "sh ...

Tips for obtaining the accurate HTML code format using Angular 2's input feature:

I am looking to retrieve all the code with an input as [input] and a tag as #tag. When attempting to obtain HTML code with jQuery using console.log($("#content")[0].outerHTML);, this is an example of how the code looks: <div dnd-droppable [dropZones]= ...

Using Jquery to iterate through a JSON array

After receiving data from a webservice, this JSON string is retrieved: [{"TITLE":"asdasdasd","DESCRIPTION":"asdasd","PORTFOLIOID":1}, {"TITLE":"sss","DESCRIPTION":"sss","PORTFOLIOID":2}, {"TITLE":"sdfsdf","DESCRIPTION":"sdfsfsdf","PORTFOLIOID":3}] Is i ...

Encountered an error while loading resource: net::ERR_CONNECTION_REFUSED in Nodejs

I am currently working on a form in my angular 6 app with nodejs, utilizing nodemailer for sending emails. Unfortunately, I am encountering an error that reads: Failed to load resource: net::ERR_CONNECTION_REFUSED : :3000/contact/send:1 Below is the form ...

What practical applications exist for preserving JSX post-transpilation of a tsx file?

While troubleshooting another issue, I decided to delve into Typescript's documentation on JSX usage. I discovered that some options involve converting JSX while others do not. I am puzzled as to why one would need to preserve JSX in transpiled file ...

Retrieve a specific key from a TypeScript interface

It seems like there might be a problem with this code snippet: interface import {BrowserService} from "../services/browser/index"; export interface IPrimaryNavigation { opts:IPrimaryNavigationOpts; } export interface IPrimaryNavigationOpts { .. ...

Compelling users to provide feedback on an App with the Ionic Framework

As a novice developer, I could use some assistance with implementing ratings in my app. My goal is to show menu items based on whether a user has given my app a 5-star rating. For instance, if a user gives a 5-star rating, I would assign the class "review ...

Custom positioning of Mui Snackbar in V5

I've been attempting to position a Snackbar in the top right corner with some customization for the top property, but I'm struggling to get it to display correctly. Here's what I've tried: import React from "react"; import { ...