Converting JSON array with ES6 functions

I have a specific array format that needs to undergo transformation.

{ [
  {
    "condition": "$and",
    "children": [
      { "column": "Title", "comparison": "$eq", "columnValue": "1" },
      { "column": "Event Status", "comparison": "$eq", "columnValue": "2" }
    ]
  },
  {
    "condition": "$or",
    "children": [
      {
        "column": "Issue Description",
        "comparison": "$lt",
        "columnValue": "3"
      },
      { "column": "Number Label", "comparison": "$gte", "columnValue": "4" }
    ]
  }
]}

The desired transformed version is as follows...

{ 
    [
        { 
            "$and" : [
                { 
                    "Title" : {
                        "$eq" : "1"
                    }
                }, 
                { 
                    "Event Status" : {
                        "$eq" : "2"
                    }
                }
            ]
        }, 
        { 
            "$or" : [
                { 
                    "Issue Description" : { 
                        "$lt" : "3"
                    }
                }, 
                { 
                    "Number Label" : { 
                        "$gte" : "4"
                    }
                }
            ]
        }
    ]
}

Several attempts using map and reduce methods have been made, coming close but not quite there yet.

This snippet belongs in a Vue project. See below for an example of the attempted code.

const result = this.parents.map(({ condition, children }) => {
        const childArray = children.reduce(
          (c, v) => ({
            ...c,
            [v.column]: { [v.comparison]: v.columnValue }
          }),
          {}
        );
        childArray.condition = condition;
        return childArray;
      });

The current output is:

[
  {
    "Title": { "$eq": "1" },
    "Event Status": { "$eq": "2" },
    "condition": "$and"
  },
  {
    "Issue Description": { "$lt": "3"},
    "Number Label&&#8221:: { "$gte&&#8221:"4"},
    "condition&&#8221:& "$or"}
]

The challenge lies in correctly placing the "condition" key in the final result.

Answer №1

Utilizing ES6 computed property names can greatly assist in allowing variable expressions enclosed within square braces [] to calculate a key value...

let inputExpressions = [
  {
    "condition": "$and",
    "children": [
      { "column": "Title", "comparison": "$eq", "columnValue": "1" },
      { "column": "Event Status", "comparison": "$eq", "columnValue": "2" }
    ]
  },
  {
    "condition": "$or",
    "children": [
      {
        "column": "Issue Description",
        "comparison": "$lt",
        "columnValue": "3"
      },
      { "column": "Number Label", "comparison": "$gte", "columnValue": "4" }
    ]
  }
];

function translateExpression(expression) {
  const translateClause = clause => {
    return { [clause.column] :  { [clause.comparison] : clause.columnValue } };
  };
  return { [expression.condition] : expression.children.map(translateClause) };
}

let resultExpressions = inputExpressions.map(translateExpression);
console.log(resultExpressions)

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

"Exploring JSON Parsers: Unlocking the Power of Single Key with

Currently facing a challenge in parsing the following data: [{ "Name": "EB DAVIE ST FS HOWE ST", "Latitude": 49.27755, "Longitude": -123.12698, "Routes": "006, C23" }] The goal is to extract all the values of "Routes", create a new rou ...

Passing unknown values to external scripts in an Angular JS controller: A step-by-step guide

I am currently working on a project that involves integrating a third-party commenting service. Within the controller, I am utilizing a factory to fetch the JSON feed for the articles. The initialization function of the controller includes the 3rd party Ja ...

Retrieving data from MongoDB with the help of ExpressJS

I am attempting to retrieve a specific value from my database individually. My collection is named: randoms Model's Name: Random Within the collection, there is one object with a 'name' field. I aim to fetch the value of 'name' an ...

What could be causing document.getElementById to return null?

I've been troubleshooting my code and noticed that one of the methods in my JavaScript file is not functioning correctly. Does anyone have any insights into why this might be happening? index.html: <!DOCTYPE html> <html lang="en"> <he ...

Streaming the request body in NodeJS using ExpressJS without buffering

Looking for a solution to process requests with no specified content-type as binary files. const app = express(); app.use(bodyParser.raw({type: (req) => !req.headers['content-type'], limit: '500mb' })); Some of these files can be ...

Setting up Webpack to compile without reliance on external modules: A step-by-step guide

I am facing an issue with a third-party library that needs to be included in my TypeScript project. The library is added to the application through a CDN path in the HTML file, and it exports a window variable that is used in the code. Unfortunately, this ...

struggling with responseText functionality in javascript

I am encountering an issue with passing variables from PHP to JavaScript using JSON. The problem lies in the fact that I am able to debug and view the items in the responseText within my JavaScript, but I am unable to assign them to a variable or properly ...

Enhance the functionality of NodeJS core applications

I recently attempted to modify some custom functions in the FS module of NodeJS, which is an integral part of NodeJS' core modules. The specific file I targeted was fs.js, located in /usr/lib/nodejs. However, despite making changes to the code, I noti ...

updateStatusCallback function is not defined in the Facebook example using jQuery

I've been trying to incorporate Facebook integration into my HTML code, specifically adding features like Facebook login and sharing functionalities. However, I've hit a roadblock in the process. Even after searching extensively for solutions, I ...

Using jQuery to initiate a page load into a new page within the WorkLight platform

I need help redirecting to a new page when the current page is loaded. My website is built using jQuery mobile in combination with WorkLight. Index.html: <body> <div data-role="importpages" id="pageport"> </div> </body> ...

"Encountering issue with Mongo's findOne method failing to retrieve data despite existence and indexing

I currently have a vast answers schema consisting of over 2 million entries. The schema structure is as follows: { user: { ...

The use of Electron require modules may lead to IntelliSense not functioning properly due to the discrepancy in working directories during runtime

Currently working on an electron-app using vs-code. I encountered some issues initially with requiring local files as modules but managed to resolve them. However, now the problem lies in the fact that I have lost intellisense for these local modules. Her ...

Executing a script containing MongoDB queries within the MongoDB shell

In my mongodb database document, I have multiple Ids that need indexing. To avoid having to repeatedly run the ensureIndex command, I want to create indexes on these Ids using a script. db.getCollection("elements").ensureIndex({customerId:1}); db.getColle ...

Tips for successfully integrating .dae files into three.js for online execution on a web browser

Hey everyone, I'm an HTML developer who has never worked with WEBGL technology before. I've been trying to figure out how to pass a .dae file into 'three.js' by searching through numerous websites, but I haven't been successful. C ...

What is the best way to invoke my Python function within my JavaScript file?

I am facing an issue with using my Python function in JavaScript. Although the actual code I am working on is more complex, I have simplified it to demonstrate the problem below: main.mjs dbutils.notebook.run("./aPythonFile.py", 5, {"parame ...

Combining array objects in Node.js

Received an array in the request body: [ { "month": "JUL", "year": "2018" }, { "month": "JAN", "year": "2018" }, { "month": "MAR", "year": "2018" } ] The input consists of two parameters (month:enum and ye ...

Encountering an "invalid query parameter" error when making a find request with FeatherJS and ReactJS

Adding $show:true to the data below results in an error when making the find request. However, when I remove $show:true, everything works perfectly with no errors. The error message states: Invalid query parameter $show. I have attempted using differe ...

Unable to access localStorage

I created a Plunker to store a value in localStorage: <!DOCTYPE html> <html> <script> localStorage.setItem('test', "hadddddha"); </script> </html> Then, I built a test page to retrieve the value from local ...

Placing elements from an array into a customized output

Currently, I am dealing with a unique output: dAmn_Raw('send chat:Sandbox\n\nmsg main\n\nthismessage'); In my code, there exists a variable: myvariable that stores a random value selected from an array I formulated. The cha ...

Tips on how to showcase up to 200 characters from a string

<?php include ($_SERVER['DOCUMENT_ROOT'].'/header.php'); include ($_SERVER['DOCUMENT_ROOT'].'/adtop.php'); if(mysql_num_rows($deals) > 0){ while($row = mysql_fetch_assoc($deals)){ echo '<div id= ...