What is the best way to generate an array from JSON data while ensuring that the values are not duplicated?

Upon receiving a JSON response from an API, the structure appears as follows:


{
    "status": "success",
    "response": [
        {
            "id": 1,
            "name": "SEA BUSES",
            "image": null
        },
        {
            "id": 2,
            "name": "BEN BUSES",
            "image": null
        },
        {
            "id": 3,
            "name": "CAPE BUSES",
            "image": null
        }
    ]
}

The objective here is to create an array of IDs in the format ids = [1, 2, 3]

Here is the JavaScript code snippet being used:


companyid = response.data.response
var ids = [];
for (var i = 0; i < companyid.length; i++){
    ids.push(companyid[i].id)
    console.log(ids)
}

However, the output is not matching expectations. The current output is displayed as:


[ 1 ]
[ 1, 2 ]
[ 1, 2, 3 ]

If anyone has any insights or suggestions, your help would be greatly appreciated.

Answer №1

let data = {
  result: "success",
  items: [
    {
      key: 1,
      title: "OCEAN TRAINS",
      picture: null
    },
    {
      key: 2,
      title: "MOUNTAIN TRAINS",
      picture: null
    },
    {
      key: 3,
      title: "DESERT TRAINS",
      picture: null
    }
  ]
};

console.log(data.items.map(element => element.key));

Answer №2

If you're unsure about what specific information you're looking for, consider adjusting your approach. For instance, to view the results only once, you can simply relocate the print statement outside of the loop:

    for (var i = 0; i < companyid.length; i++){
       ids.push(companyid[i].id)
    }   
    console.log(ids)

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 on using the $.grep() method in jQuery to filter dynamic inputs

When using the "grep" function in jQuery to filter data, the code sample below works well for static conditions. However, if the "name" and "school" parameters have multiple values, how can we filter them? Let's say I receive the name and school from ...

Methods like jQuery blink(), strike(), and bold() offer dynamic ways to manipulate

I'm currently tackling an inquiry. The code I crafted seems to be functioning without any issues: (function () { if($('#target:contains("bold")')) { $('#target span:first').css('font-weight','bold ...

Having difficulty changing the value of a Select element in AngularJS

Struggling to update the select value from AngularJs. Check out my code below: <select ng-model="family.grade" > <option ng-repeat="option in options" value='{{option.id}}'>{{option.text}}</option> </s ...

Eliminate items/attributes that include a certain term

Is there a way in Node.js to remove all fields or objects from a JSON file that have a specific word (e.g. "test") as their name, and then return the modified JSON file? Take a look at an example of the JSON file: { "name": "name1", "version": "0 ...

What are the steps to compile Sencha Touch using sencha-touch.jsb3?

I've been working on modifying the bundled sencha-touch.jsb3 file in an effort to decrease the size of the framework code. Here's what I've done so far: First, I downloaded the Sencha SDK Tools from I then made edits to SenchaTouch/sen ...

Display the JSON data by pressing Enter key instead of clicking on the submit button

I am facing an issue with my MVC view where clicking the submit button posts data using Ajax to the Controller. The controller returns a JSON result containing messages which are then displayed on the View. The problem arises when I press Enter after seein ...

Learning to retrieve and implement information from a JSON document in Angular7

I'm attempting to retrieve data from a JSON file and present it in a formatted manner. Link to the JSON FILE: https://raw.githubusercontent.com/datameet/railways/master/trains.json Here is the code I'm using, but encountering an error in the fe ...

Hiding elements in FireBase and Angular based on user identification

Currently venturing into the world of Firebase in conjunction with AngularJS after previously working with php and server-side rendered pages. I am grappling with how to securely hide specific parts of an application from certain users. I have three disti ...

In JavaScript, I would like to be able to input an end date and have the program calculate and display the number of days remaining until the deadline

I'm working on a school project that involves JavaScript code. I'm struggling with converting a date prompt from string to number format. As a beginner in JavaScript, I could really use some guidance. <script> enddate = prompt('Wh ...

When incorporating axios within an express route, it is causing the data field to display unusual characters instead of JSON

I've been grappling with this issue for quite some time now, and any assistance would be greatly appreciated. Initially, I attempted to resolve the problem by utilizing the Moralis nodeJs library. While it worked fine on my local environment, it retu ...

using the image source in the onclick function

I have implemented the following code to convert an image to grayscale using Javascript. <body> <canvas id="myCanvas" width="578" height="400"></canvas> <script> function drawImage(imageObj) { var canvas = document.getElement ...

Ways to hide the value from being shown

I have integrated jscolor (from jscolor) to allow users to pick a color with an input field. However, I am facing issues in styling it as I'm unable to remove the hex value of the selected color and couldn't find any relevant documentation on av ...

What is the best way to implement a recursive service call that is triggered automatically at regular intervals?

I came across this code snippet: us.isConnected() .then(function (msg) { er.msg = msg }, function (msg) { er.msg = msg }); $interval(function () { us.isConnected() .then(function (msg) { er.msg = msg }, function (msg) { er.msg = msg }); }, ...

Converting JSON to TypeScript in an Angular project

Within my Angular project, I have an HTTP service that communicates with a web API to retrieve JSON data. However, there is a discrepancy in the naming convention between the key in the JSON response (e.g., "Property" in uppercase) and the corresponding pr ...

Developing a function utilizing text data

Deciding to dive into Vue and Javascript, I attempted to streamline some code but ended up doing the opposite. So here's the issue: I have a data object in vue: eventOptions: { eventType: { data: [], ...

Load Vue dynamically to implement reCAPTCHA script

I am looking for a way to dynamically load a script like recaptcha specifically within the Register.Vue / login.Vue component. <script src="https://www.google.com/recaptcha/api.js?onload=vueRecaptchaApiLoaded&render=explicit" async defer> </s ...

Exploring ways to access an element's background color through JavaScript

Is there a way to access an element's CSS properties that are set by a class name in JavaScript? In the case of the first div element, I have applied a "red" class which sets its background color to red. However, when I try to access the div's b ...

Insert a MongoId into a PHP array using the push function

During my search for feed owners, I encountered an issue when trying to push the MongoId of the $_SESSION user. To ensure that the ID is in the correct format for MongoId, I used the following code: new MongoId($_SESSION['user_information'][0][ ...

Is there a list (collection) feature in nodejs similar to that in Java?

Is there a list collection type concept in nodejs similar to dynamic arrays? I need this kind of dynamic array functionality for my nodejs coding. Are there any concepts such as list or something similar available in nodejs? My code snippet is provided ...

Sending the wrong callback response in a Volley request callback

I recently encountered a strange issue while using Volley for making requests in my Android app. I added a callback to handle the response, but when I initiated two requests from different activities, the second request was returning the response of the fi ...