Sort through an array of objects by their specific key names

I have a collection of objects structured as shown below:

var data = [
    {
        abc: { name:"abc" }
    },
    {
        new_abc:  {name:"hello" }
    },
    {
        def: { name:"def" }
    },
    {
        ghi: { name:"ghi" }
    },
    {
        new_ghi: { name:"world" }
    },
    {
        new_jkl: { name:"javascript" }
    },
    {
        lmn: { name:"lmn" }
];

I am interested in retrieving only the objects containing keys starting with "new". Among the array elements above, there are 3 such objects.

The desired output should be as follows:

[
    {
        new_abc:{name:"hello"}
    },
    {
        new_ghi:{name:"world"}
    },
    {
        new_jkl:{name:"javascript"}
    },
]

Answer №1

Here are the steps you can take:

var data = [
 {
  abc:{name:"abc"}
 },
 {
  new_abc:{name:"hello"}
 },
 {
  def:{name:"def"}
 },
 {
  ghi:{name:"ghi"}
 },
 {
  new_ghi:{name:"world"}
 },
 {
  new_jkl:{name:"javascript"}
 },
 {
  lmn:{name:"lmn"}
]


results = data.filter(entry => Object.keys(entry).some(key => key.indexOf('new') === 0));
console.log(results);

Answer №2

I'm interested in specifically selecting objects with keys that begin with "new"

To achieve this, you can utilize the Array#filter method along with String.prototype.startsWith() as shown below.

const data = [{abc:{name:"abc"}},{new_abc:{name:"hello"}},{def:{name:"def"}},{ghi:{name:"ghi"}},{new_ghi:{name:"world"}},{new_jkl:{name:"javascript"}},{lmn:{name:"lmn"}}];

console.log(data.filter(item => Object.keys(item)[0].startsWith('new')));

The startsWith() function checks if a string starts with another specified string and returns either true or false.

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

Is this code correct for passing a variable to another form?

$("#delete").click(function() { deleterecord(); }); function deleterecord(){ var id = $("#iduser").val(); alert("aw"+id); var id = $('#iduser').attr(); e.preventDefault(); pressed = "delete" $.ajax({ ...

Change the value of an input button in an HTML tag without assigning any value to it

Currently, I am utilizing the UserWP plugin on my WordPress registration page. The button on the form currently reads "Submit Query," which I find to be subpar. I would much prefer it to say "Register" instead. Unfortunately, there doesn't seem to be ...

Displaying an HTML string on a webpage

I am developing a user dashboard using Django for a Python-based web application. This web application generates emails, and the HTML content of these emails is stored in a file (and potentially in a database table as well). As part of the dashboard's ...

Is there a way to divide a string in half without relying on pointers?

Is it possible to enter a string that always contains an even number of letters and have it displayed with the two halves separated by a hyphen? I've been able to successfully print the first half of the word, but I'm struggling with printing the ...

Do not fulfill the promise until all the images have finished loading

Below is the intended process: Iterate through a collection of img tags Retrieve each tag's src URL Convert it to a base64 encoded string using an HTML 5 canvas Once all images have been converted, resolve the promise and call the callback function ...

Exploring the power of Socket.io in conjunction with Node.js, Express, and Jade

I'm having trouble using Socket.io to test if a client is connected. I've tried different approaches and suspect that my mistake might be in the app.get function. I even attempted moving this to a separate route js file, but it didn't yield ...

Tips on how to showcase up to 200 characters from a string

<?php include ($_SERVER['DOCUMENT_ROOT'].'/header.php'); include ($_SERVER['DOCUMENT_ROOT'].'/adtop.php'); if(mysql_num_rows($deals) > 0){ while($row = mysql_fetch_assoc($deals)){ echo '<div id= ...

Perform time update every second

Is it feasible to have my timeupdate function run every second? (Using VUE CLI) @timeupdate="videoSecond" videoSecond(){ let Second = this.player.currentTime(); let CaptureList = this.capturesList; CaptureList.forEach(element => ...

Cease the execution of a task in Express.js once the request timeout has been

Suppose we have the following code snippet with a timeout of 5 seconds: router.get('/timeout', async (req, res, next) => { req.setTimeout(5000, () => { res.status(503) res.send() }) while (true) { ...

The error message states: "Cannot create element as the React object is not

Recently delving into the world of React and Material UI, I've been working on creating an AppBar with nested Tabs. Here's a snippet of my current approach: import {React, PropTypes, Component} from 'react'; import TodoTextInput from & ...

Guide to sending an array to a Node.js web service using AngularJS

Attempting to add an array of data to a Node.js web service using the code below. $scope.addList = function(task,subtask){ subtask.checked= !(subtask.checked); var data = { "taskId": task._id, "subTaskName": subtask.subTaskNa ...

Learn how to dynamically chain where conditions in Firebase without prior knowledge of how many conditions will be added

Currently, I am working on a project using Angular and firebase. My goal is to develop a function that can take two arguments - a string and an object, then return an Observable containing filtered data based on the key-value pairs in the object for a spe ...

Exclude the property during the iteration when duplicating an array

Currently, I am in the process of creating a new array based on the data retrieved from my database. The original array contains multiple objects, some of which are identical like the one shown below: object(stdClass)[26] public 'id' => str ...

The React syntax is malfunctioning

componentDidMount() { const restaurants = Restaurant.all() restaurants.then( rests => { this.setState({ restaurants: rests }) }) } render() { const { restauran ...

Library for JavaScript English Dictionary

Looking for recommendations for a reliable JavaScript library focused on English dictionaries. I need to access the definitions of input words, so an external library is needed. ...

The array is coming back empty after attempting to add objects to it

My Node JS and Express JS controller code is below: const UserComment = require(".../model/UserComment"); router.post("/get/comments", async (req, res) =>{ try{ let currentUserID = req.body.userID; let myUserComment = await UserComment.find({userID: cu ...

When handling cross-domain Jquery Ajax requests, the error function may unexpectedly return a success status

While attempting a cross domain GET request using jQuery AJAX, I am encountering a situation where the error function returns success as the status. The data I am expecting to be returned from the get service is: document.write("<div class=\"displ ...

Dealing with CORS, IIS7, and PHP - Overcoming the Access-Control-Allow-Origin obstacle

I am attempting to enable another local host (such as javascript.dev) to make a xhr request to this particular host, which operates on an IIS7 server. When I perform a curl -I command, the headers I receive are as follows: HTTP/1.1 200 OK Content-Length: ...

Encountering issues with running NPM on my Ubuntu server hosted on Digital Ocean

After successfully installing node (nodejs), I encountered a persistent error when attempting to use NPM. Despite researching the issue extensively and trying different solutions, I have been unable to resolve it. Here is the error message displayed in th ...

Updating Bootstrap modal content based on button clickExplanation on how to dynamically change the content

I am looking to dynamically change the content displayed inside a modal based on the button that is clicked. For example, clicking button one will only show the div with the class 'one' while hiding the others. $('#exampleModalCenter&a ...