Search through the JSON data, identify similar values, and save them in a collection

Struggling to find a way to limit the output of my comparison between attribute values in an object, I am only looking for one output per ID.

Any suggestions?

//example JSON

var obj1 = {
"Summary" : 
[
    {
        "ID" : "1234", 
        "Name" : "John", 
        "Status" : "Green",
    },
    {
        "ID" : "5678", 
        "Name" : "Mike", 
        "Status" : "Green",
    },
    {
        "ID" : "9012", 
        "Name" : "Tom", 
        "Status" : "Red",
    }

]
};

//my code

var attributesvalues = ["Mike", "Green", "Red"];
var sg1 = [];
var k;
var l;


//push name of each attribute value to a new array
//one example
sg1.push(attributesvalues[0]);

 //go through each ID, if name value exist, push "1", else push ""
 for (k = 0; k < obj1.Summary.length; k++) {
 for (l in obj1.Summary[k]) {
    if (sg1[0] == obj1.Summary[k][l]){
    sg1.push("1");
    }
    else{
    sg1.push("");   
    }
 }

 }

The desired output should be - 4 values, name + a "1" or "" for each ID(3)

sg1 = ["Mike", "", "1", ""]
sg2 = ["Green", "1", "1", ""]

Instead, the current output is - the name + a "1" or "" for each attribute.

sg1 = ["Mike", "", "", "", "", "1", "", "", "", ""]
sg2 = ["Green", "", "", "1", "", "", "1", "", "", ""]

Any additional guidance or tips you can offer would be highly appreciated. Still trying to get the hang of JS.

Answer №1

You can only determine if there is a match after completing the entire for-in loop.

let found;

for (m = 0; m < data.Info.length; m++) {
    found = "";
    for (n in data.Info) { 
        if (data.Info[i][n] == search[0]) {
            found = "1";
            break;
        }
    }
    search.push(found);
}

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

Extracting information from Postgres and converting it to JSON format while dynamically updating the column names

Is there a way to selectively import specific columns from a table in json and alter their names during the process? For example: MyTable (id, column1, column2, columns3) I aim to transform them into json format as follows: MyTable: {column11, column2, ...

Utilizing Prolog to process incoming Json posts

<pHello there, this is my very first question on stackoverflow so please be patient with me.</p> <pI am working on creating a simple Prolog API that can receive JSON posts and then send back another JSON post after processing. I came acr ...

Adjust the size of each link in the highchart network diagram

Is it feasible to individually set the length of each link in a network graph using highcharts? I am interested in creating a visualization where each user is displayed at varying distances from the main center user. I have been experimenting with the lin ...

Troubleshooting the issue: Incompatibility between jQuery .focus() and dynamically generated list items from ng-repeat in AngularJS

I am currently working on enhancing the keyboard accessibility of a website, specifically focusing on making a dropdown menu accessible via keyboard. I am attempting to establish focus on the element with the id= list-0. Below is the HTML code snippet: & ...

Encountering a JavaScript toJSON custom method causing a StackOverflow error

Unique Scenario Upon discovering this answer, a new idea struck me - creating an object from a JSON literal. This led me to believe I could do the opposite using the handy JSON method: JSON.stringify(myObject). Curious, I proceeded as follows: function ...

SonarQube flagging a suggestion to "eliminate this unnecessary assignment to a local variable"

Why am I encountering an error with SonarQube? How can I resolve it since the rule page does not offer a specific solution? The suggestion is to eliminate the unnecessary assignment to the local variable "validateAddressRequest". validateAddress() { ...

How to modify the content type in an Angular.js $http.delete request

When making a $http.delete request in my Angular app, I include a config object using the following approach: return $http.delete('projects/' + projectID + '/activityTypes', {data: [{id: 2}]}) This method attaches the values from my d ...

Transitioning the height of a Vue component when switching routes

I've been struggling to implement a transition slide effect on my hero section. The height of the hero is set to 100vh on the homepage and half of that on other pages. Despite trying various methods, I haven't been able to get it working properly ...

Analyzing the functionality of Express with Mocha and Chai

Currently facing an issue with testing my express server where I am anticipating a 200 response. However, upon running the test, an error occurs: Test server status 1) server should return 200 0 passing (260ms) 1 failing 1) Test server statu ...

Vue automatically refreshes momentjs dates prior to making changes to the array

I am dealing with a situation where my child component receives data from its parent and, upon button click, sends an event to the parent via an event bus. Upon receiving the event, I trigger a method that fetches data using a Swagger client. The goal is ...

What is the best method for transferring an array from PHP to JAVASCRIPT using AJAX and JSON?

Could use some assistance here. It seems like I am receiving a string instead of an array. After passing the array, which is the result of a SQL query from PHP to JavaScript through AJAX, I want to loop through the array and populate certain fields in a fo ...

Retrieve Javascript files from the local static directory

Currently, I am developing a small project with Nuxt JS and I am facing a challenge in calling some Javascript files from my static directory. When it comes to CSS files, I have been able to do it successfully using the following code: css: [ './stat ...

Deleting an item from a serialized array using jQuery

I am currently exploring methods to remove an item from a serializedArray based on its index. Take the following scenario: [ { 'name' : 'item1', 'value' : '1' }, { 'name' : 'item2', &ap ...

What causes inability for JavaScript to access a property?

My current coding project involves the usage of typescript decorators in the following way: function logParameter(target: any, key : string, index : number) { var metadataKey = `__log_${key}_parameters`; console.log(target); console.log(metadataKey ...

What is the function of the OmitThisParameter in TypeScript when referencing ES5 definitions?

I came across this specific type in the ES5 definitions for TypeScript and was intrigued by its purpose as the description provided seemed quite vague. /** * Removes the 'this' parameter from a function type. */ type OmitThisParameter<T> ...

json.net encountering issues with parsing nested objects

I'm currently facing a challenge in creating an object from a JSON string. The tricky part is that I won't always know the number or names of the keys involved. Here's what I've attempted so far: The JSON data: { "browser":"Chrome ...

Vue table displaying a list of books with a button that allows users to easily send the title of the

Hey everyone, I am new to Vue and struggling with a certain task. I have two tables: Books and Booking. Books: ID, NAME, AUTHOR etc. Booking: ID, ID_USER, ID_BOOK I'm creating a page in Vue that displays all bookings, but the table only shows the BOO ...

How can one access Firestore Timestamp in its raw format?

We are facing an issue with serializing JSON data when working with Firestore as our database. While it is recommended to use the TimeStamp object for writing dates to Firestore, we have encountered a challenge. I have a converter that handles converting ...

Error detected in JSON syntax... Where is it hiding?

After running the code through jsonlint, it flagged an error on line 17. However, upon close inspection of the file which contains about 1000 lines, I couldn't pinpoint the issue. It's possible that the problem lies further down the file, but I w ...

A guide on removing an element from a state array in a React functional component for a To-Do List application

I need help making a to-do list item disappear when clicked. The deleteHandler method is not working as expected. Can anyone provide logic on how to filter out the clicked item? import React, { useState } from 'react'; const ToDoList = () => ...