I must develop a custom function that generates a pure JavaScript string with the 'name' index and includes all the 'props'

My code is almost correct, but instead of returning a ':' in the Json result as desired, it returns a ','. Is there a way to achieve the desired result without modifying the JSON string like I did with the "replaces"?

I am searching for a more elegant solution that doesn't involve removing the array brackets from the Json expression. Can you help me find a better approach?

    // JSON Object  
    var items  = [
      {
        name: "item 1",
        id: 2,
        props: {
          a: "a prop1",
          b: "b prop1",
        },
        values: [1, 2, 3],
      },
      {
        name: "item 2",
        id: 3,
        props: {
          a: "a prop2",
          b: "b prop2",
        },
        values: [6, 1, 2, 3, 4],
      },
      {
        name: "item 3",
        id: 4,
        props: {
          a: "a prop3",
          c: "c prop3",
        },
        values: [10, 1, 2, 3, 4, 5],
      },
    ];

    export function getObject(items) {
    
    var arr = [];
    
      for(var i in items){
        arr.push(items[i].name);
        arr.push(items[i].props);
      }
    
      var myJSON = JSON.stringify(arr).toString();
      
      var test = myJSON.replace("[","{").replace("]","}"); // I couldn't find another way to extract the array data from the array brackets.
      
      var test2 = JSON.stringify(test);
    
    // The current output of test2 is: "{\"item 1\",{\"a\":\"a prop1\",\"b\":\"b prop1\"},\"item 2\",{\"a\":\"a prop2\",\"b\":\"b prop2\"},\"item 3\",{\"a\":\"a prop3\",\"c\":\"c prop3\"}}"  
    // But the expected output should be:  "{\"item 1\":{\"a\":\"a prop1\",\"b\":\"b prop1\"},\"item 2\":{\"a\":\"a prop2\",\"b\":\"b prop2\"},\"item 3\":{\"a\":\"a prop3\",\"c\":\"c prop3\"}}"
          
       return test2;
    }

Answer №1

To convert each item into an object with a single property, use the .map method. The key of the property should be item.name, and the value should be the item.props object:

const createObject = items => items.map(item => ({ [item.name]: item.props }));

// JSON Object  
var items = [{
    name: "item 1",
    id: 2,
    props: {
      a: "a prop1",
      b: "b prop1",
    },
    values: [1, 2, 3],
  },
  {
    name: "item 2",
    id: 3,
    props: {
      a: "a prop2",
      b: "b prop2",
    },
    values: [6, 1, 2, 3, 4],
  },
  {
    name: "item 3",
    id: 4,
    props: {
      a: "a prop3",
      c: "c prop3",
    },
    values: [10, 1, 2, 3, 4, 5],
  },
];

console.log(createObject(items));

If you require a JSON string instead of an object, wrap it with JSON.stringify. (Keep in mind: There's no such thing as a "JSON Object".)

const createObject = items => JSON.stringify(items.map(item => ({ [item.name]: item.props })));

// JSON Object  
var items = [{
    name: "item 1",
    id: 2,
    props: {
      a: "a prop1",
      b: "b prop1",
    },
    values: [1, 2, 3],
  },
  {
    name: "item 2",
    id: 3,
    props: {
      a: "a prop2",
      b: "b prop2",
    },
    values: [6, 1, 2, 3, 4],
  },
  {
    name: "item 3",
    id: 4,
    props: {
      a: "a prop3",
      c: "c prop3",
    },
    values: [10, 1, 2, 3, 4, 5],
  },
];

console.log(createObject(items));

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

Tips for effectively using $interval for ongoing polling in AngularJS?

Within my Angular codebase, I have implemented long polling functionality using the following code snippet: var request = function() { $http.post(url).then(function(res) { var shouldStop = handleData(res); if (!shouldStop()) { ...

What are some alternative ways to begin a photo album besides always using the first image

I have a gallery with 5 thumbnail images previewed, but there are more photos in the gallery. Instead of cluttering my code and hiding them with CSS, I am seeking an alternative solution. Below is my current HTML code: <div id="start_slides2"> ...

Retrieving JSON data through the use of retrofit and rxjava

I'm trying to retrieve JSON data from a specific URL using Retrofit and RxJava. You can find the sample JSON data at this link: . Here's a snippet of the JSON: { "data": [ { "itemId": "1", "desc": "Batcave", "audio": "https://storage.googl ...

Using a URL in an AJAX request

Before redirecting to another page, I am storing data from a textbox. When the user clicks the back button on the page load function in JavaScript, I retrieve the data from the textbox using: var pageval = $('#grid') .load('/Dealer/AllClai ...

In Javascript, check if an item exists by comparing it to null

I am working with a dropdown list that can be used for various types of data. Some of the data includes an isActive flag (a BOOLEAN) while others do not. When the flag is absent, I would like to display the dropdown item in black. However, if the flag exis ...

Calculating response time in Selenium with VB.NET: A comprehensive guide

I'm working on creating an automated test to calculate the average response time for a screen's responsiveness. My tools of choice are Selenium and VB.net. Can someone please provide guidance on how to accurately calculate this? The waitforpage() ...

Deleting the initial line in a JSON reply

My current code is : $.getJSON("https://www.domain.com/someapi/callback=?", function(data){ $.each(data, function(i,item){ alert(item.x); }); }); I am currently facing an issue with my JSON response because there is ...

Serializing JSON data in C# involves converting objects or data structures

I need to retrieve 2 distinct columns values from the Country Master table in JSON format using C#. However, I am encountering an error message that says "Object reference not set to an instance of an object." Below is my code snippet: using System; usi ...

Leveraging image values for selecting an image from a collection and showcasing it (Javascript)

I have a collection of images that I want to enlarge upon clicking. Here is what I currently have: <div class="gallery"> <div> <img src="content/imggallery/img1.jpg" class="oldimg" value="0"> </div> ...

The JSON array retrieved from the $http.GET request is coming back as undefined, which is not expected

Presenting my code below: function gatherDataForGraph(unit, startTs, endTs, startState, endState){ points = []; console.log('/file/tsDataPoints/'+unit+"?startDate="+startTs+"&endDate="+endTs+"&startState="+startState+"&endState="+en ...

Steps to retrieve the central coordinates of the displayed region on Google Maps with the Google Maps JavaScript API v3

Is there a way to retrieve the coordinates for the center of the current area being viewed on Google Maps using JavaScript and the Google Maps JavaScript API v3? Any help would be greatly appreciated. Thank you! ...

Unable to designate decimal value as the default in DropdownListFor in ASP.NET Core when utilizing JavaScript

Everything appears to be functioning properly, except when dealing with decimal values in the following code snippet: $('select#listspec_0__qty option[value = 105.3]').attr("selected", true); ...

I am looking to include both the type and maxLength attributes in a MUI TextField

<TextField value={ele.mobile} helperText={ferrors[id]?.mobile} name="mobile" classes={{ root: classes.textField }} InputProps={{ clas ...

Troubleshooting Nested JSON Data Iteration in Python

I've been dabbling with Python and running into issues while trying to loop through a JSON data file to access specific keys and values. While I'm quite comfortable doing this in PHP, I'm finding it more challenging in Python for some reason ...

Is there a way to sort through nested objects with unspecified keys?

I'm looking to extract specific information from a nested object with unknown keys and create a new array with it. This data is retrieved from the CUPS API, where printer names act as keys. I want to filter based on conditions like 'printer-stat ...

When attempting to send a request for the JSON body to Node.js using the await fetch method, I encountered an issue

Recently, I started working with node js and attempted to fetch JSON data using the code below: const req = await fetch( "http://localhost:3000/api/auth/signin", { method: "POST", header:{ 'Accept':&apo ...

Place the image on the canvas and adjust its shape to a circle

Here is the code I used to insert an image into a canvas: <script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script> <button onclick="addTexttitle()" type="button" class="text-left btn-block btn white">Set Imag ...

Display a preview of a CSV file in a datagrid after uploading

My goal is to upload a csv file to the backend and show a preview of the data on the same page without refreshing or reloading. I believe using AJAX is the way to achieve this. I am curious about how we can accomplish this with Ajax and jQuery in the cont ...

Having trouble with a basic API Get request?

I'm trying my hand at making a simple get request to fetch a random quote from an API. When I hardcode the change of the quote on button click, everything works smoothly. $(document).ready(function() { $("#quotebtn").on('click', functio ...

Unable to cancel $interval within factory

I created a factory for long-polling, complete with start and stop methods. However, I am struggling to cancel the timer. Any suggestions or ideas? app.controller("AuthCtrl", function($scope, $http, $window, User, Poller) { Poller.start(1, $scope.sess ...