Simplify nested JSON array using lodash or deepdash

There is a nested json array that needs to be flattened and key values (onSale, newComing) removed. Below are two JSON structures: the original and what is desired. Tools being used include Javascript-lodash-deepdash.

Original JSON:

[
  {
    "id": 1,
    "model": "Google Pixel 3",
    "image": "/src/assets/images/high-angle-app-learning-new-language-phone_23-2148293463.jpg",
    "path": "/src/assets/images/high-angle-app-learning-new-language-phone_23-2148293463.jpg",
    "price": 799,
    "quantity": 2
  },
  ...
]

Desired JSON:

[
  {
    "id": 1,
    "model": "Google Pixel 3",
    "image": "/src/assets/images/high-angle-app-learning-new-language-phone_23-2148293463.jpg",
    "path": "/src/assets/images/high-angle-app-learning-new-language-phone_23-2148293463.jpg",
    "price": 799,
    "quantity": 2
  },
  ...
]

Attempts with _.reduce and _.flatmap have been unsuccessful. Assistance is appreciated.

Answer №1

flatMap is the way to go.

const array = [ { "id": 1, "model": "Google Pixel 3", "image": "/src/assets/images/high-angle-app-learning-new-language-phone_23-2148293463.jpg", "path": "/src/assets/images/high-angle-app-learning-new-language-phone_23-2148293463.jpg", "price": 799, "quantity": 2 }, { "id": 2, "model": "Samsung Note 9", "image": "/src/assets/images/samsung-1283938__340.jpg", "price": 999, "quantity": 2 }, { "newComing": [ { "id": 10, "model": "Samsung Galaxy A7 (2020)", "image": "/src/assets/images/Samsung S7.jpg", "price": 533, "quantity": 2 }, { "id": 12, "model": "Samsung Galaxy A7 (2018)", "path": "https://media.istockphoto.com/photos/new-ios-14-screen-iphone-apples-next-operating-system-for-its-to-be-picture-id1270790424?k=20&m=1270790424&s=612x612&w=0&h=p_1DGqUriFPLKnt1KNbtRwdxJkB0ozk...
const flatten = array.flatMap(({newComing, onSale, ...item}) => newComing || onSale || [item]);
console.log(flatten);

const lodash = _.flatMap(array, ({newComing, onSale, ...item}) => newComing || onSale || [item]);
console.log(lodash);
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8fe3e0ebeefce7cfbba1beb8a1bdbe">[email protected]</a>/lodash.min.js"></script>

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

An issue occurs when trying to use the Redux Toolkit error object as a child element

I am facing an issue while trying to extract a task from the Tasks file and add it to Slice. There seems to be a problem in the 'addTask' method in the task section. Any assistance would be greatly appreciated. import React from 'react&a ...

Implementing a JavaScript Function to Retrieve a Value When a Button is Clicked

<!DOCTYPE html> <html> <body> <button id="one">Try it</button> <h1>JavaScript Functions</h1> <p id="demo"></p> <script> var x=document.getElementById("one").addEventListener("click", onefunction); ...

Unity fails to deserialize JSON data and does unable to return any result

After using Jsonutility to read a json file, I am facing an issue where the values of the class are showing as 0 when checked. Despite looking for similar questions, I continue to encounter either 0 or null values after Deserializing. It seems like the pro ...

Verifying X-editable input in Laravel (Server-side)

I've successfully integrated x-editable into my webpage (). When I click on a field, it becomes editable inline, allowing me to make changes and submit them to a POST URI. Currently, I am sending three key-value pairs: array:3 [▼ "name" => "n ...

An array of NSObjects and boolean values

Is it possible for an NSArray to store an array of boolean values? The code snippet below demonstrates this: BOOL isTrue = NO; NSMutableArray *boolArray = [[NSMutableArray alloc] init]; [boolArray addObject:[NSNumber numberWithBool:isTrue]]; NSLog(@"Th ...

Retrieve value associated with object key containing character:

Trying to extract reviews from iOS, where the key includes a colon in the middle. For example: im:rating: {attributes: {…}} Thus, attempting something like this is unsuccessful: {entry.im:rating.label} What is the best way to retrieve the label from i ...

Spotting repeated terms within an HTML document

I have a table with results generated using v-html (meaning the text inside the table does not appear until the page is rendered). I want to compare two rows and highlight any duplicate words they may contain. While looking for examples, I came across a p ...

Creating code to ensure a div element is displayed only after a specific duration has elapsed

Can anyone help me with coding to make a div appear on a website after a specific amount of time? Here's an example of what I'm trying to achieve: <div class="container"> <div class="secretpopout"> This is the hidden div that should ...

Mapping nested JSON in the Log-stash HTTP Output: A Step-by-Step Guide

Utilizing Logstash to send JSON messages to an API. The "mapping" attribute is being used to establish message mappings. Below is a snippet of the shipper configurations: output { stdout { } http { url => "http://localhost:8087/message ...

The design of RESTful web applications with a client-server architecture

I need clarification on how client-server architecture should function for a modern web application with a RESTful backend. For a web app, the client is typically the browser while the server is the web server. Programatically speaking, there are componen ...

Success Turns Sour with jQuery Ajax Error

I've been experimenting with Mustache.js and the GitHub API, but I encountered an issue when trying to load more results that don't actually exist. I was hoping to display a message or generate an error in such cases, but my attempts have not bee ...

What is the best way to modify a particular value buried within a JavaScript object?

Within my node project, I am working with a JavaScript object like the one shown below: that.responseData = { fields: { id: { label: 'ID', value: objectRecord.id, info: '', ex ...

A function cannot be used with Random Song Loop

Recently delving into the world of JavaScript, I encountered a peculiar issue. When attempting to execute the following code within a function, nothing displays in the console. Yet, after testing it without the function, the expected strings appear as inte ...

"Why does the useEffect in Next.js fire each time I navigate to a new route

Currently, I have implemented a useEffect function within the Layout component. This function is responsible for fetching my userData and storing it in the redux-store. However, I have noticed that this function gets triggered every time there is a route c ...

"Interactive table feature allowing for scrolling, with anchored headers and columns, as well as the option to fix

I'm in need of a table that has certain requirements, as shown in the image. https://i.stack.imgur.com/Z6DMx.png The specific criteria include: The header row (initially blurred) should remain fixed when scrolling down the table The first column s ...

error in routing using koa-router with koa

I've been diving into learning Koa and trying out some basic exercises, but I'm having trouble implementing a simple routing feature. I followed the code from this tutorial and here's what I have so far: var koa = require('koa'); v ...

React Native Navigator screen displaying unexpectedly

I am currently utilizing React Navigation within my react native application and following its authentication flow. The app.js file will determine whether to render the authentication screen or home screen based on the user's authentication state, wh ...

How can one generate JSON using JsonBuilder in groovy?

Can someone provide the structure of an object that can be converted into the following JSON format? { "header":{ "callbackUrl":"", "clientOrderId":"A565132", "clientOriginationId":"2345FE", "serviceProvider":"VERIZO ...

Processing JSON output from an API request

When I make an API call, I receive the response in JSON format and need to filter out only the values for sys_name. I am facing difficulty as my JsonConvert.DeserializeObject() method is returning blank. { try { using (HttpClient client = ...

React Js: Error encountered while parsing JSON due to an unexpected token < at the beginning

I am having issues fetching my JSON file in React JS using the fetch method. An error is popping up that says: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 I am unable to figure out what the error could be, even after va ...