Guidelines for duplicating an object into three separate objects with underscore.js

Hey there, I receive my JSON data as an object in the following format:

    {
        "id": "001724",
        "select": false,
        "class": "product",
        "Names": [
          "A",
          "B",
          "C"
        ],
        "available": true,
        "description": "selected product",
        }

I am looking to organize and sort this JSON data using Underscore.js in my JavaScript file. My goal is to create new objects based on the names within the existing object and add a "name" attribute to each one of them.

[{
A:[
0:{
    "name":"A"
   "id": "001724",
   "select": false,
   "class": "product",
   "available": true,
   "description": "selected product"

}
]
B:[
0:{
    "name":"B"
   "id": "001724",
   "select": false,       
   "class": "product",
   "available": true,
   "description": "selected product"
}
]
C:[
0:{
   "name":"C"
   "id": "001724",
   "select": false,
   "class": "product",
   "available": true,
   "description": "selected product"
}
]
default:[
0:{
    "name":"B"
   "id": "001724",
   "select": false,       
   "class": "product",
   "available": true,
   "description": "selected product"
}
]
}]  

In addition, the default array will contain the same data as the 'B' array.

I am currently working on accomplishing this task using underscore.js library.

Answer №1

Have you attempted the following:

let newObject = _.cloneDeep(obj);

Answer №2

In JavaScript, you have the ability to clone an Object easily by using the Object.create method:

if(!Object.create){
  Object.create = function(o){
    function F(){}; F.prototype = o;
    return new F;
  }
}
var clonedObject = Object.create(originalObject);
var anotherClonedObject = Object.create(originalObject);

By cloning the object, you create a separate instance that is independent from the original, even if the variable names differ.

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

What is the downside of exporting all components into one index.js file?

My approach involves exporting all components to an index.js file, allowing me to easily import them into any other file with the code snippet below. This method is not only straightforward but also keeps my code cleaner. import { RocketCard, Container, Na ...

What is the best way to dynamically update a variable in React JS by utilizing the Date() function in the background?

My code is designed to increase the value of the strong variable every 10 seconds in the background using the Date() module import React, { useState, useEffect } from "react"; export default function App() { const [strong, setStrong] = useStat ...

Retrieving jQuery UI Autocomplete Suggestions from a JSON Source

I'm struggling to parse a JSON file for use with jQuery UI autocomplete. The JSON structure is not as organized as I had hoped, with keys being IDs like {"140":"Abarth","375":"Acura"}. Here's the link to my development page: Below is my JavaScri ...

I'm getting an error about uncaught products in a collection - can you help me understand what this means and how to

My next.js website, which fetches products from Shopify, was working flawlessly until a few months ago when it suddenly stopped building on the development server. Now, whenever I try to run the website locally, I am encountering a "Cannot read properties ...

Leverage the enhanced speed of Jackson for efficient serialization of objects containing oneToMany mappings

Sharing some insights on using Jackson for serializing objects with one-to-many mappings and returning the response in string format. This is my Class Structure: @Entity public class Order { /* All the fields associated with this class ...

Execute tests on changing files using cypress.io

I'm currently experimenting with using Cypress to test a large Angular application that I've developed. What I want to achieve is to load an expectation file into my test and then run the test based on this expectation file. Despite trying diffe ...

The react-leaflet-heatmap-layer-v3 source directory could not be located

Upon attempting to utilize the npm package react-leaflet-heatmap-layer-v3 in my React TypeScript application, I successfully installed it and ran yarn start. However, I encountered the following warning messages: WARNING in ./node_modules/react-leaflet-hea ...

Transmitting multiple JSON parameters with Retrofit 2

Here is the method in the interface: @FormUrlEncoded @POST (“url/myurl") Call<JsonArray> sendParameters (@Header("x-imei") String imei, @Header("x-id-cliente") String idCliente, @Field(“param1") JsonObject param1, @Field(“param2") JsonArray pa ...

Flexible Array Properties within Custom Object

Trying to construct a unique object from server feedback that contains constant fields plus an object array is my current task. I'll refer to it as a DynamicResponse. Each instance of DynamicResponse will have the same kind of custom objects in its ar ...

When promises are passed in AngularJS, the $asyncValidator may throw an error stating "Undefined is not a function!"

I am currently in the process of refactoring my code, with the intention of achieving the following structure: Services: } }]).factory('UsernameRESTService', ['Restangular',function(Restangular){ var restAngular = Resta ...

It is not possible to assign multiple values to three different variables simultaneously

Request curl -XGET http://my_host:9111/api/issues/search?componentKeys=my_poject&facets=severities&p=1&ps=1 Response: { "total": 10057, "p": 1, "ps": 1, ... If I want to extract keys: "total", "issues", "facets.values". I can try the following b ...

Integrate Angular 2 into the current layout of Express framework

After generating an express structure with express-generator, I ended up with the standard setup: bin bld node_modules public routes views app.js package.json Now, I want to enhance the views and routes directories by organizing them as follows: v ...

Ways to utilize the Math.max and Math.min functions within an Array

Attempting to use this approach on an array to retrieve both the minimum and maximum values proved unsuccessful. var array = [3, 6, 1, 5, 0, -2, 3]; var min = Math.min( array ); var max = Math.max( array ); document.write(max); ...

The Google Books API initially displays only 10 results. To ensure that all results are shown, we can implement iteration to increment the startIndex until all results have

function bookSearch() { var search = document.getElementById('search').value document.getElementById('results').innerHTML = "" console.log(search) var startIndex = I have a requirement to continuously make Ajax calls ...

Having trouble locating an element, Sammy?

I am encountering an issue while using Sammy for my SPA. The error message I receive is: [Sun Mar 29 2020 17:37:19 GMT+0300 (Eastern European Summer Time)] #main 404 Not Found get / Error: 404 Not Found get / at Sammy.Application.error (sammy-latest ...

Distinguishing between an Android SDK method and a method I have created

Currently, I am attempting to utilize GSON for JSON parsing within an AsyncTask. One obstacle I have encountered is the presence of both android.os.AsyncTask.getStatus and my custom getter method for my own class, Status, which represents the parsed JSON ...

What is the best way to incorporate text transitions using jquery?

Recently, I've come across this code snippet: $('#slider_title').text(var); This line of code successfully adds the text stored in a variable to the paragraph identified by the id "slider_title". And now, my goal is to smoot ...

What is the best way to join together the deserialized QnAResponse string instead of using a {filename}?

Within this documentation, there is a demonstration of the QnA Maker service executing REST calls and parsing JSON responses - Step 3: How to link Luis with QnA The specific module section I am referring to looks like this: /* START - QnA Maker Response ...

Add inline CSS to the <html> element using TypeScript when clicked on

My experience with TypeScript is still new, and I recently found myself confused when trying to apply inline CSS to a tag on click. I initially thought it would be simple, but in TypeScript, things seem to work differently. I attempted to use document.quer ...

Extract values from JSON object and store them in an array, then apply them in an external

I have created an axios JSON data call function and I am looking for a way to extract values from my jJSON function so that they can be used outside of the function. Is there a method to achieve this? Below is my code snippet: let website_names = `${api} ...