Tips for verifying elements using the Loop technique in a JSON array

I am new to JavaScript and I have been trying to run the following code with an expected result like this:

[["00:04:12","05:54:46"],["06:06:42","12:45:22"],["12:51:11","15:56:11"]]

However, my script is not working as expected. Can someone please help me identify what's wrong with my code? Thank you

<!DOCTYPE html>
<html>

<body>
    <p>Access a JSON object :</p>
    <p id="demo"></p>

    <script>
        var myObj;
        var m1 = [];
        myObj = [{
            "machine": "M-MBH-(2)",
            "time": [{
                "start": "06:24:23",
                "end": "16:45:37"
            }]
        }, {
            "machine": "M-MD2.5",
            "time": [{
                "start": "00:04:12",
                "end": "05:54:46"
            }, {
                "start": "06:06:42",
                "end": "12:45:22"
            }, {
                "start": "12:51:11",
                "end": "15:56:11"
            }]
        }];

        for (var i in myObj) {
            var obj = myObj[i].time;
            if (obj === "M-MD2.5") {
                obj.forEach(function(time) {
                    var pair = [];
                    pair.push(time.start);
                    pair.push(time.end);
                    m1.push(pair);
                });
            }
        }

        document.getElementById("demo").innerHTML = JSON.stringify(m1);
    </script>

</body>

</html>

Answer №1

If you want to retrieve a matching element and then create a new array using JavaScript, you can utilize the .find() method followed by .map():

let myData = [{
        "device": "Laptop",
        "specs": [
            {
                "cpu": "Intel i5",
                "ram": "8GB"
            }
        ]
    },
    {
        "device": "Smartphone",
        "specs": [
            {
                "storage": "128GB",
                "model": "iPhone 12"
            },
            {
                "storage": "64GB",
                "model": "Samsung Galaxy S20"
            }
        ]
    }];

let output = myData.find(x => x.device === "Smartphone").specs.map(({storage,model}) => [storage,model]);

console.log(output);

Answer №2

To achieve the desired outcome, modify the if condition to verify the machine as shown below

myObj[i].machine ==="M-MD2.5"

Here is a code snippet for reference:

    <!DOCTYPE html>
            <html>
            <body>
            <p>Access a JSON object :</p>
            <p id="demo"></p>

            <script>
            var myObj;
            var m1=[];
            myObj = [{
                    "machine": "M-MBH-(2)",
                    "time": [
                        {
                            "start": "06:24:23",
                            "end": "16:45:37"
                        }
                    ]
                },
                {
                    "machine": "M-MD2.5",
                    "time": [
                        {
                            "start": "00:04:12",
                            "end": "05:54:46"
                        },
                        {
                            "start": "06:06:42",
                            "end": "12:45:22"
                        },
                        {
                            "start": "12:51:11",
                            "end": "15:56:11"
                        }
                    ]
                }];

                for(var i in myObj)
                {
               var obj = myObj[i].time;
               if(myObj[i].machine ==="M-MD2.5"){
            obj.forEach(function(time) {                    
                var pair=[];
                pair.push(time.start);
                pair.push(time.end);
                m1.push(pair);
            });
                 }
              }

            document.getElementById("demo").innerHTML = JSON.stringify(m1);
            </script>

            </body>
            </html>

Problem: The value of the obj variable represents time and comparing it with the machine name will always result in false.

Answer №3

Simple solution utilizing filter, map, and Object.keys

JSON.stringify(
  ...myObj
    .filter(element => element.machine === 'M-MD2.5')
    .map(element => element.time.map(subElement => Object.values(subElement)))
);

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

Expanding and shrinking the index within a specific circular boundary in JavaScript

I'm dealing with a circular range of ASCII values from a to z, where each letter corresponds to a number between 97 and 122. I have no issue with increasing the value within this range, but I am struggling when it comes to decreasing it. For example ...

Steps to access a JSON file in Angular.JS locally without utilizing a server

Below is the code for my controller: angular.module('navApp', []).controller('blogCtrl', function($scope, $http) { $http.get("../json/blogs.json").success(function(response) {$scope.blogs = response.blogs;}); }); I am trying to fi ...

Utilizing the correct method for binding checkboxes in Vue JS for effective two-way communication

I am working with data retrieved from a MySQL database where "1" and "0" represent boolean true and false. In my Vue component, I have set these values as shown below: data(){ return { form : { attribute_1 : "1", //attribute 1 is true ...

Using the Tailwind CSS framework in combination with Vue's v-html

My vue component is designed to accept a prop of raw HTML, which originates from a wysiwyg editor utilizing tailwind classes for styling - similar to our vue app. The issue arises when using v-html="responseFromAPI" in my component, as the raw H ...

The loading animation does not appear in the NextJS 14 - loading.tsx component while a GET request is being processed

Component with 500 photos displayed on my page: 'use client'; import { useEffect, useState } from 'react'; import { wait } from '@/components/loaders/skeletons'; export default function Postings() { const [photos, setPhotos ...

Transferring data from jQuery Ajax to PHP

I'm facing a challenge in retrieving a value back to PHP that I can manipulate and save to the database. It appears that using the GET method with jQuery AJAX is not yielding the desired results. Below is the PHP code snippet where I attempt to captur ...

In my chat application, I encountered the error message "Received an expression instead of an assignment or function call - no-unused-expressions"

While working on my React Chat app and trying to access my Firebase, I encountered the error message: "Expected an assignment or function call and instead saw an expression no-unused-expressions" The error seems to be related to the assignment of this.rem ...

Tips on harnessing the power of PhantomJS and node.js for web scraping

After successfully installing node-phantom using the command npm install node-phantom, I encountered an error when running this code: Cannot find module 'webpage' var webpage = require('webpage').create(), url = "https://www.exampl ...

When I engage with the input field, it ceases to be in focus

Here is the code I've been working on: https://github.com/Michael-Liendo/url-shortener/blob/main/src/pages/index.js If you want to see the issue for yourself, check it out at: ...

JS Issue with Countdown functionality in Internet Explorer and Safari

I am having an issue with a JavaScript countdown not working on Internet Explorer and Safari, despite being tested on Windows 7. It works fine on Chrome and Firefox. I am unable to switch to a jQuery countdown due to certain restrictions on the website, so ...

Ensure that parameters are validated correctly in the Next.JS application router using the searchParams method

When building the page, I need to properly validate params in the Next.JS app router using searchParams. My goal is to show a main image (coverImage) for each photo on the /gallery page. When a photo is clicked, I want to display more photos of the same k ...

What is the reason behind the array.map() function not altering the original array?

I attempted to increment each element of my array by one, but was having trouble. Here is what I tried: myArray=[1,2,3] myArray.map(a=>a+=1) // also tried a++ and a=a+1 console.log(myArray) // returns [ 1 , 2 , 3 ] Unfortunately, this method did not w ...

Filling in a text field with the text content (rather than the value) from a dropdown menu

Presently, I have the select box with the id "title" populating a text field with the id "costcenter". The current code works perfectly fine when using the VALUE of the select box to trigger the population of the cost center field. However, my requirement ...

Is it possible for the Vue computed function to use destructuring assignment for the parameter even when no arguments are provided?

new Vue({ el: "#app", data: { value: "text", }, computed:{ all: function({value}){ return value } } }); <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"> ...

Tips for rendering nested objects and arrays within Angular 2

I am receiving JSON data from an API on the back-end and I want to display it using ngFor. However, when I tried to do so, I encountered an error message stating: "Cannot find a differ supporting object '[object Object]'" in the console. To addr ...

Maintain dropdown menu visibility while navigating

I'm having an issue with my dropdown menu. It keeps sliding up when I try to navigate under the sub menu. I've spent all day trying to fix it, testing out various examples from the internet but so far, no luck. Any help would be greatly apprecia ...

Uploading base64 arrays from AngularJS to a Node.js server: Allowing Access-Control-Origin

My current challenge involves sending an array of base64 strings from my Client Side (AngularJs) to my NodeJs Server. However, I've encountered a peculiar situation. When I attempt to send an object containing the base64 data along with other properti ...

Can we streamline this jQuery code by utilizing .hasClass and .bind?

Can this code be simplified? Initially, when #griffyindor has the 'active' class, I want all other houses (slytherin, ravenclaw, and hufflepuff) to show. If at any point it loses the 'active' class upon clicking something else, I want ...

Vue: Implement out-in transition where the incoming element appears before the outgoing element has completely disappeared

Check out my code on Codepen: here In this scenario, I have set up two div elements: Block 1 and Block 2. The functionality I am looking for is when a button is clicked, Block 1 smoothly translates to the left until it goes out of view. Once that happens ...

Error in Angular timer causing NaN result

Struggling to create a timer in JavaScript, a basic one at that. I wrote what I thought was correct code, but it's not functioning properly - resulting in the textbox value changing to NaN after just one second. Below is the code snippet: <timer ...