convert json formatting to a string

Can anyone assist me in resolving this issue?
I am trying to achieve the following format:

true: 2,3,4
false: 5

I am using sequelize, I am struggling with outputting JSON correctly
Please see my code snippet below. However, it is not functioning as expected.

const test = {
    one: {
        'user': '2',
        'status': '1', block: {
            'ok': 'false'
        }
    },
    two: {
        'user': '3',
        'status': '1', block: {
            'ok': 'false'
        }
    },
    three: {
        'user': '4',
        'status': '1', block: {
            'ok': 'false'
        }
    },
    five: {
        'user': '5',
        'status': '0', block: {
            'ok': 'true'
=======
    }
}
const grouped = test.reduce((groups, test) => ({
    ...groups,
    [test.user]: [...(groups[test.user] || []), test.block.ok]
}), {});
const text = Object.entries(grouped).map(([key, values]) => `${key}: ${values}`).join('\n');
console.log(text)

Answer №1

This appears to be the solution you are seeking.

true: 5
false: 2,3,4

It is not possible to simplify the object because it is an Array prototype. You must first convert your test object into an array using Object.values and then group them by true and false.

const test = {
  one: {
    user: '2',
    status: '1',
    block: {
      ok: 'false',
    },
  },
  two: {
    user: '3',
    status: '1',
    block: {
      ok: 'false',
    },
  },
  three: {
    user: '4',
    status: '1',
    block: {
      ok: 'false',
    },
  },
  five: {
    user: '5',
    status: '0',
    block: {
      ok: 'true',
    },
  };
const grouped = Object.values(test).reduce(
  (groups, group) => {
    groups[group.block.ok].push(group.user);
    return groups;
  },
  { true: [], false: [] },
);
const text = Object.entries(grouped)
  .map(([key, values]) => `${key}: ${values}`)
  .join('\n');
console.log(text);

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

consistent character spacing for a custom font upload

Developing an application that necessitates counting up and opting for the font Orbitron due to its square appearance. The issue arises as, unlike the default chrome font, the width of this font's digits is not consistent, causing the count character ...

Set up Vue.prototype prior to the component loading

In my Vuejs code, I am utilizing the plugins feature to define a global shared variable. Vue.use(shared) The shared variable is defined as follows:- export const shared = { config: getAppConfig() } shared.install = function() { Object.definePropert ...

Tips for utilizing 'safe-json-stringify' within Angular 4 Application

I have a specific requirement to convert a JSON object to a string. However, simply using JSON.stringify() does not work due to circular references. After some research online, I came across a package that can handle this issue for me. The only problem is ...

"Recall the act of pressing a button on a

Is there a way to make my website remember if the mute button was pressed? Currently, the website plays music with a mute button, but it doesn't retain the mute setting when navigating to a new page or refreshing the current page. The local storage sc ...

Is it possible to use CSS to create a gap between the cursor and the placeholder text within an input field?

Could you please assist me with a bug I have encountered on an older version of Firefox for OSX (37.0.2)? I have included a screenshot of the issue here: https://i.sstatic.net/dzK0G.png Is there a way to use css to move the first character of the placehol ...

Looking to learn how to utilize the setInitial method in Java programming?

Can someone help me write a method in Android Studio using setInitial(int[] x) to set the first 3 indices of an array to specific values (10, 100, and 342) and then return the modified array? I am struggling with this assignment and need assistance within ...

Clear the cache following the service call

I am currently working on a service that has two methods. Utilizing the built-in cache support for $resource, I am trying to implement a way to refresh the cache when a service call is made from the controller. I attempted to use $cacheResource without suc ...

Developing a Multi-Faceted Array Utilizing SQL Data

The requirement of the plugin I am using is to provide it with an array structure in JavaScript that looks like this: var data = [ { "id": 1, "name": "University1", "list": [ {"id": 1, "name": "Dorms", "list": ...

Exclusive event triggered in Blazor only upon changing the page location

Just starting out with Blazor. I've been working on a Blazor project that utilizes DevExpress components, causing some issues with scrolling. My goal is to have the page start at the top every time I navigate to a new page. Currently, I've found ...

Uncover the secrets to retrieving JSON data using the React fetch method

I've been struggling to retrieve data from an API using various methods, but without success. I have included my code and the API below in hopes of utilizing this JSON data with the React fetch method. // Fetching Data from API fetchData() { ...

Is there a way to automatically start a YouTube video using JavaScript?

Is it possible to automatically play a YouTube embedded video after a visitor has been on the site for a certain amount of time, without affecting view count? I am looking for a JavaScript solution that can accomplish this without having to modify the em ...

Content in the <core-animation-pages> element is extending beyond the borders of the main DIV when the "slide-from-right" effect is applied (Polymer

Check out this quick video I made to demonstrate the issue: I have successfully incorporated core-animation-pages into my web application. I have three different divs that transition using the slide-from-right animation without any problems. However, in d ...

NodeJS - Bluebird: implementing a loop with a waiting mechanism for completion

Struggling with a seemingly simple task in my NodeJS and MongoDB project. I've included Bluebird for promises, but need some help. In my code, I have a basic for-loop that generates random names and pushes them into an array: const PlayerGenerator = ...

Retrieving a PHP variable from HTML without using a form

Is there a way to pass a variable from HTML to PHP without using a form and the traditional post or get methods? I have tried using the code provided, but I am unable to access the value of the 'buy1' variable in PHP. Is there a way to achieve th ...

In SQL, setting default values in a string is a common practice

//I am attempting to incorporate default variables into my SQL string to avoid syntax errors when loading my code. However, for some reason, adding the if statement is not producing any results. {`var serversLength = Request.Form("servers").count; v ...

In TypeScript version 2.4.1, the fontWeight property encounters an error where a value of type 'number' cannot be assigned to the types of '"inherit", 400'

When attempting to set the fontWeight property in TypeScript, I encounter the following error: Types of property 'test' are incompatible. Type '{ fontWeight: number; }' is not assignable to type 'Partial<CSSProperties>&a ...

The React-Native app freezes on the splash screen when running on iOS, while it functions perfectly on Android

My React-Native 0.62.3 app is not working on iOS. It launches, receives the bundle from metro, and then just displays the splash screen without any further action. Here's the run log: flipper: FlipperClient::addPlugin Inspector flipper: FlipperClient: ...

Is it possible for SqlCommand.ExecuteReader to automatically open the database connection?

Unusual behavior is happening on my website. I have a WCF Data service that provides JSON data to populate a jqGrid using javascript/ajax calls. In addition, there is server-side code that also accesses the same WCF service to retrieve data. Within my WC ...

What is the process for reading server responses following the delivery of an alert to a designated user through socket.io?

Recently, I started exploring Socket.io and encountered an interesting challenge. My goal is to retrieve real-time location data from an Android device. To achieve this, I developed a basic application to access the current GPS coordinates. Additionally, I ...

Local development and the same origin policy: a necessary pairing

While working on my Ember front end calling a Spring/Rest/MongoDB backend running locally for development, I encountered a same origin policy error. I am curious about the common workarounds for this issue. Below is the code snippet I'm using: App = ...