How can I extract certain key-value pairs from an array and add them to a different array?

collection

[{
    "title":"Completed",
    "details":[[dateA,timeA],[dateB,timeB]]
},{
    "title":"Unfinished",
    "details":[[dateC,timeC],[dateD,timeD]]
}]

If I need to transfer the title "Unfinished" and details [dateC,timeC] to a separate array, what is the method to accomplish this?

Answer №1

Start by identifying the object within the array using its key. Let's say your array is stored in a variable named mylist

var issue = mylist.find(function(item){ return item.key === 'Failed'; });

Now, if you have a new array:

var failedList = []; // your new array
failedList.push({
    key: issue.key,
    values: issue.values[0] // assuming you only need the first value
});

There might be a more efficient way to accomplish this. It would be helpful if you can provide additional details on your desired outcome.

UPDATE:

If your intention is to extract all failed results from the array and organize them into a subgroup, you can utilize the reduce method as shown below.

var failedList = mylist.reduce(function(accumulator, item) {
    if(item.key === 'Failed'){
        var data = {
            key: issue.key,
            values: issue.values[0]
        };
        accumulator.push(data)
    }
    return accumulator;
}, []);

Answer №2

Applying pure JavaScript

let failedItems = [];

for(let i=0; i<array.length; i++){
 if (array[i]['status'] === "Failed"){
    failedItems.push(array[i]);
  }
}

failedItems now holds all the failed entries.

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 updating an element in an array by using another element from a separate array

What is the objective? We have two arrays: orders and NewOrders We need to check for any orders with the same order_id in both arrays. If there is a match, we then compare the order status. If the order from the NewOrders array has a different status, w ...

The disappearance of HTML DOM nodes event

When I relocate certain DOM nodes from one context to another, some of the child nodes end up losing their event listeners. HTML <div><lots of nested nodes .../><div> <div> <div> <div#newNode></div> < ...

Switch the text display by clicking on a different button in the list

I am currently dealing with an issue involving a list of boxes containing text/images and buttons for expanding/collapsing the text. Whenever I click on another item's button, the text box that was previously opened gets closed, but the button text re ...

Is it possible to initially design a login page using HTML/CSS and JavaScript, and then integrate VUE into it?

As part of a school project, I am tasked with developing a web-based application for a library system. The goal is to create a platform where librarians can login and manage books by adding, removing, or editing them. My responsibility lies in handling the ...

What is the best way to handle multi-dimensional JSON data without keys in JavaScript?

My JSON data is structured as follows: { "bitcoin": [ "-0.47", "-0.46", "-0.42" ], "maker": [ "8.29", "8.29", "6.89" ] } I want to extract values from this data where keys are not specified. How can I achieve this? Update: Tha ...

Javascript functions function properly only if they contain the 'alert()' command

My aim is to utilize Ajax (Javascript + php) for checking user name availability when a user moves focus to another form field. The strange part is that my functions only work when I include some alert(), without them, the functions fail to operate. Anoth ...

Desktop display issue: Fontawesome icon not appearing

Having trouble getting the fontawesome icon to display properly on my website. It appears in inspect mode, but not on the actual site itself. Any suggestions on how to fix this issue? import React, { Fragment, useState} from "react"; import { Na ...

Enable and disable subscriptions in real-time to control the amount of cached data and prevent the error message "Uncaught TypeError: Converting circular structure to JSON"

In an attempt to control the cache on the client side, we had the idea of toggling the subscription to a specific Collection on and off by placing the Meteor.subscribe call within a reactive context as recommended in the Meteor documentation - "In addition ...

Is it possible to implement CSS code from a server request into a React application?

With a single React app that hosts numerous customer websites which can be customized in various ways, I want to enable users to apply their own CSS code to their respective sites. Since users typically don't switch directly between websites, applying ...

Mongoose retrieves the entire document, rather than just a portion of it

I'm currently experiencing an issue with my mongoose query callback from MongoDB. Instead of returning just a specific portion of the document, the code I'm using is returning the entire document. I have verified that in the database, the 'p ...

The Angular.copy() function selectively copies properties and does not duplicate everything

Exploring a function within a service: $scope.addPeriod = function(newPeriod) { if(newPeriod.from !== '' && newPeriod.until !== '') { var index = $scope.newPeriods.indexOf(newPeriod); ...

Express.js continues to retrieve outdated query results that have already been removed from the database

I am experiencing a strange issue with my PostgreSQL and Express.js setup. Despite updating my database with new entries and deleting old ones, it seems to only display the old data that was deleted days ago. It's almost as if it's stuck in some ...

Creating an array of objects data is a breeze with Vue.js

I have an array of data containing selected items, and I need to extract the IDs from this array into a new array so that I can send only the IDs to the back-end. Sample Code method toggleSelection(rows) { console.log('this.multipleSelection : &a ...

Troubleshooting vague errors with uploading large files in Golang's net/http protocol

I've encountered a challenging error while uploading large files to a server built with Golang's default net/http package. The upload process is defined as follows: uploadForm.onsubmit = () => { const formData = new FormData(uploa ...

Oops! The connection timed out while trying to format the error in SMTPConnection

Encountering an error with a connection timeout while trying to send emails using nodemailer. Seeking assistance as the console keeps showing this error message: Error: Connection timeout at SMTPConnection._formatError (/home/codabae/Desktop/mailmonster/B ...

Implementing the insertion of a <div> element within an input field using jQuery

<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></scr ...

When the specified width is reached, jQuery will reveal hidden circular text upon page load instead of keeping it hidden

My current issue involves utilizing jQuery to hide circular text when the window width is below 760px. Although the functionality works as intended, there is a minor problem when the page loads under 760px width - the text briefly shows up before hiding ag ...

Rerender not occurring after array splice with React hooks setter

My parent component structure is as follows: import React from "react"; import Test from "./Test"; function App() { const [configs, setConfigs] = React.useState([1, 2, 3]) return ( <div> ...

Unable to include the variable "$localStorage"

While working on my method in app.js, I encountered the following error: Uncaught Error: [$injector:strictdi] function($rootScope, $q, $localStorage, $location) is not using explicit annotation and cannot be invoked in strict mode http://errors.angula ...

NuxtJs: Oops! It looks like NuxtError is not defined in this context

Exploring NuxtJs is new to me. I decided to experiment with how nuxt-link functions by purposely setting up a nuxt-link to a non-existent route in order to trigger the default 404 page. Here's the line of code I added to the pages/index.vue file: < ...