How can I use JSON path to extract all the elements within an array from a JSON input?

I want to extract all fields from a JSON array and turn it into a flat JSON file. Here is an example of the input:

Array JSON input:

{
    "field1": "ALNT12345",
    "field2": "ALNT345346",
    "field3": "2015353423",
    "field4": "2332124343",
    "arrayfield1": [
        {
            "arr1": "625347",
            "arr2": "rere"
        },
        {
            "arr1": "634441",
            "arr2": "sdfsd"
        }
    ]
}

The goal is to convert the above array JSON into 2 separate records like this, using JSON path:

Required Output:

[
  {
    "field1": "ALNT12345",
    "field2": "ALNT345346",
    "field3": "2015353423",
    "field4": "2332124343",
    "arr1": "625347",
    "arr2": "rere"
  },
  {
    "field1": "ALNT12345",
    "field2": "ALNT345346",
    "field3": "2015353423",
    "field4": "2332124343",
    "arr1": "634441",
    "arr2": "sdfsd"
  }
]

In my attempt with JSON path,

$.arrayfield1.*

It only retrieves array fields. If JSON path doesn't work for this, can you recommend a JavaScript code to retrieve all the fields?

Thanks.

Answer №1

Consider giving this a try:

var obj = {
    "fieldA": "ALPH12345",
    "fieldB": "ALNT345346",
    "fieldC": "2015353423",
    "fieldD": "2332124343",
    "arrayField1": [
        {
            "arrVal1": "625347",
            "arrVal2": "example1"
        },
        {
            "arrVal1": "634441",
            "arrVal2": "example2"
        }
    ],
    "arrayField2": [
        {
            "arrVal1": "625347",
            "arrVal2": "example1"
        },
        {
            "arrVal1": "634441",
            "arrVal2": "example2"
        }
    ]
};

console.log(transform(obj));

function transform(obj) {
    var singleLevel = {};
    var multiLevelArr = [];
    for(var key in obj) {
        var value = obj[key];
        if(typeof value != "object") {
            singleLevel[key] = value;
        } else {
            multiLevelArr = multiLevelArr.concat(value);
        }
    }

    for(var x in multiLevelArr) {
        for(var y in singleLevel) {
            multiLevelArr[x][y] = singleLevel[y];
        }
    }

    return multiLevelArr;
}

Click the link below to test your code:

https://fiddle.jshell.net/06zfn55L/2/

Answer №2

Consider trying something similar:

check it out here

let newData = [];
data.arrayfield1.forEach(function(entry) {
    let keys = Object.keys(data);
    let obj = {};
    keys.forEach(function(key){
        if(Object.prototype.toString.call(data[key]) !== '[object Array]') {
            obj[key] = data[key];
        }
        let subkeys = Object.keys(entry);
        subkeys.forEach(function(subkey){
            obj[subkey] = entry[subkey];
        });
    });
    newData.push(obj);
});

Answer №3

Consider trying out Array.prototype.map(), for in loops, and Array.prototype.forEach()

let data = {
    "field1": "ABCD12345",
    "field2": "EFGH67890",
    "field3": "9876543210",
    "field4": "1357975315",
    "arrayfield1": [
        {
            "arr1": "246813579",
            "arr2": "qwerty"
        },
        {
            "arr1": "975318642",
            "arr2": "asdfgh"
        }
    ]
};

let result = data.arrayfield1.map(function(value, key) {
 let object = {};
 for (let index in data) {
  if (!Array.isArray(data[index])) {
   object[index] = data[index]
  }
 }
  let names = Object.keys(value);
  names.forEach(function(val, idx) {
    object[names[idx]] = value[val]
  })
 return object
});
 
console.log(JSON.stringify(result, null, 2))

Answer №4

Give this a shot :-

let data = {
    "name": "John Doe",
    "age": 25,
    "city": "New York",
    "phone": "555-555-5555",
    "pets": [
        {
            "type": "dog",
            "name": "Rex"
        },
        {
            "type": "cat",
            "name": "Whiskers"
        }
    ]
};



let modifiedData = [];

if(data.hasOwnProperty('pets')) {
    data.pets.forEach(function(pet){
        let newData = JSON.parse(JSON.stringify(data));
        delete newData.pets;
        for(prop in pet) {
            newData[prop] = pet[prop];
        }
        modifiedData.push(newData);
    });
}   

console.log(modifiedData);

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

Looking for a way to assign customized thumbnails to images in react-responsive-carousel and react-image-magnifiers?

I am currently working on a product viewer using react-responsive-carousel and react-image-magnifiers. Following an example from this GitHub repository, I encountered an issue with mapping custom thumbnails correctly. Although hard-coding the array works f ...

Utilize Autocomplete component from Material UI to sift through distinct option values

Looking to implement unique options in the dropdown menu of an Autocomplete component from Material UI based on a specific property within a list of objects. The current issue is that duplicate values are appearing in the dropdown, like ['Color1&apos ...

Can you explain the functionality of isolate scope in angularjs?

I'm having trouble grasping the concept of scope : {}. Here's a snippet of code I've been working on. Why does it always display "strength" in the console instead of the actual array value? // Code goes here var app = angular.module("super ...

Images in Android webview disappearing after first load

When it comes to loading a local HTML file with local images into a WebView on Android, everything seems to work fine on emulators and newer devices. However, I encountered an issue with a much older device running Android 2.3.4. Initially, the images disp ...

Techniques for converting a variable into an array in vue.js

I am attempting to output a variable as an array like [ 'Google', 'Facebook', 'Twitter', 'Apple', 'Oracle' ] However, the result I am receiving is: Google Facebook Twitter Barishal Oracle The code I have ...

Struggling to transfer JSON data between Python and PHP?

I've encountered a strange issue recently. I have a Python script that is called from a webpage using PHP, and it returns a JSON object with approximately 20 variables. Everything seems to be working fine except for one variable that always returns an ...

Using a combination of JQuery, HTML, and CSS, create a unique set of random colors for each box simultaneously

Seeking assistance in individually changing the color of each square element that is generated one at a time in a row of five, with an id="square" tag. When I click the clickMe() function, I want each square to randomly change color. However, currently onl ...

Assigning administrator privileges with connect-roles and Passport.JS

I've been struggling to create an admin role for accessing a simple admin page following the documentation provided by connect-roles. I'm currently retrieving the admin status from the database and storing it in a global variable, but I'm un ...

Why won't my div tag show conditionally with AngularJS ng-show?

I'm having trouble displaying a div tag on a form based on the boolean flag specified in ng-show. Unfortunately, the div is not showing up at all. Here's what I've tried so far without success. Any assistance would be greatly appreciated! F ...

Setting innerHTML does not affect the content of an SVG element

I am currently working on an Angular 7 application and I need to dynamically update the text value based on a dropdown selection. For example, if the id of the text element is 10, then I want to change the text from 'hi' to 'hello'. T ...

Having trouble retrieving the URL from JSON data - every time I attempt to access it, it just shows as undefined. Any suggestions

Having trouble extracting the URL from JSON, as it shows undefined. Any suggestions? <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" ></meta> <script language="JavaScript" type="text/javascript" ...

Once the form has been submitted, proceed to open a new page following processing

Trying to remove an entry or offer from the database and then return to the page with all entries/offers. Attempted using Javascript, but it successfully deletes the item without redirecting to the overview page. Is this the correct approach with Javascri ...

Send a variable to a background script and access it in various functions across tabs without relying on the storage API

I have encountered an issue where I am passing a string variable to the background script from a plugin (called from the popup.html), but I am unable to use my variable outside of the listener function in the background script. In my plugin.js file: chro ...

Uncovering the JavaScript Linked to a Specific Element

Is there a way to link directly to the JavaScript controlling a particular HTML element, unlike the typical "inspect element" approach which is limited to HTML and CSS? ...

Unraveling Nested JSON into Nested Structs with Golang

Consider the code snippet below: type Input struct { Value1 string Value2 string Value3 string Value4 string Nest } type Nest struct { ID string } input := &Input{} decoder := json.NewDecoder(r.Body) if err : ...

Utilizing AJAX to load a WAV file

One of the tasks I'm working on involves a collection of audio files. When a file from this list is clicked, I want JavaScript to load and display the waveform of that specific audio file. The following function is responsible for drawing the wavefor ...

My function handler is not being triggered when using React's onClientClick

I'm facing an issue with a button component I have, let's refer to it as < MyButton >. <MyButton onClick={this.props.calculate} onClientClick={this.changeColor} > Calculate </MyButton> Whenever I click the button, my cal ...

Definition of TypeScript type representing the value of a key within an object

As I delve into defining custom typings for a navigation library using TypeScript, one challenge that has me stumped is creating a navigate function. This function needs to take the Screen's name as the first argument and the Screen's properties ...

What is the best way to ensure that my image completely occupies the div?

I am facing a challenge in creating a hero image that would completely fill the div on my webpage. Despite setting the width and height to 100%, the image seems to only occupy half of the space. Check out the CSS and HTML code snippet here. div.hero{ ...

Converting a Multidimensional Array into JSON Using ServiceStack

Why is the property "coordinates" being excluded from the JSON when returning the following object? [Route("/GeozonePolygon/{ZoneType}")] public class RequestGeozonePolygon{ public int ZoneType { get; set; } } public class ResponseGeozonePolygon{ ...