Tips for filtering an array based on a specific condition:

I am working with an array:

results = [
  {"Created Date ": "20181012", "Created By ": "A", "Job Number ": "001", "Department": "FS"},
  {"Created Date ": "20181012", "Created By ": "B", "Job Number ": "002", "Department": "DS"},
  {"Created Date ": "20181012", "Created By ": "C", "Job Number ": "004", "Department": "FS"}
]

The values in the array might look like this sometimes (column order changed and no blank characters, but column names remain consistent):

results = [
  {"Created By": "A", "Department": "FS", "Created Date": "20181012", "Job Number": "001" },
  {"Created By": "B", "Department": "DS", "Created Date": "20181012", "Job Number": "002"},
  {"Created By": "C", "Department": "FS", "Created Date": "20181012", "Job Number": "004"}
]

Now, I want to extract a new array that includes only the values of three specific columns - "Created By", "Created Date", and "Job Number", in a specific order. The resulting array should look like this:

results = [
  {"20181012", "A", "001"},
  {"20181012", "B", "002"},
  {"20181012", "C", "004"}
]

Do you have any suggestions on how to achieve this?

Answer №1

It is important to note that objects do not have a reliable ordering, so the concept of a first or second column is irrelevant.

However, if you have specific keys for which you need the corresponding values, you can utilize the map function and consider variations of the key to account for any discrepancies:

var results = [{
    "Created Date ": "20181012",
    "Created By ": "A",
    "Job Number ": "001",
    "Department": "FS"
  },
  {
    "Created Date": "20181012",
    "Created By ": "B",
    "Job Number ": "002",
    "Department": "DS"
  },
  {
    "Created Date": "20181012",
    "Created By ": "C",
    "Job Number ": "004",
    "Department": "FS"
  }
]

var output = results.map(d => [
  d['Created Date'] || d['Created Date '],
  d['Created By'] || d['Created By '],
  d['Job Number'] || d['Job Number ']
]);

console.log(output);

Answer №2

This example showcases an alternative approach to using the map() method of an Array object:

var results = [{
"Created Date ": "20181012",
"Created By ": "A",
"Job Number ": "001",
"Department": "FS"
  },
  {
"Created Date": "20181012",
"Created By": "B",
"Job Number": "002",
"Department": "DS"
  },
  {
" Created Date": "20181012",
" Created By": "C",
" Job Number": "004",
"Department": "FS"
  }
];

Array.prototype.remove = function(index){
  this.splice(index,1);
}

var nu_arry = results.map(item => {
  let d = [];
  let keys = Object.keys(item);
  keys.remove(3);  // remove Department key name
  keys.forEach(function(key) {
    d.push(item[key]);
  });
  return d;
});
console.log(nu_arry);

Regardless of spaces before or after a key name, the code effectively identifies all keys using Object.keys(). The flexibility of this solution allows for easy modification of key names without impacting functionality, as there are no hardcoded keys. Note: the use of arrow functions eliminates the need for separate user-defined functions.

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

Enhance your Google Line Chart by incorporating HTML into the tool tip feature

I'm looking to enhance the tooltip for the Cats line chart by adding an additional line of text. Note: My note goes here.. When hovering over the cats chart, I would like the tooltip to include: Jan 1, 2020 Cats:10, percent: 0% In addition to t ...

What is the technique for adjusting the background while rotating the corner?

Is it possible to position a background image in the corner while rotating another image? rotate: $('#ship').css({ transform: 'rotate(' + corner + 'deg)' }); } move background: starx[i]=starx[i]+... s ...

Transferring information from a React Native user interface to an Express server

I'm currently learning React and working on a MERN stack project. I've been facing an issue with passing a variable from the frontend to the backend. Despite using console logs for debugging, I noticed that my request body is empty. I've ded ...

What is the best way to modify the Angular ng-src output to use the 'data-src' attribute instead of 'src'?

Incorporating the OwlCarousel jquery plugin with an ng-repeat situation in one of my views looks like this: <div owl-carousel-item="" ng-repeat="item in items" class="item"> <img id="image{{ $index }}" data-ng-src="http://uploads.mysite.c ...

Performing repeated insertion using a foreach loop

I am seeking a way to add multiple rows into a database table. This is the HTML code: <tr> <td style="display:none"><input type="text" rows="4" name="teste[]" value="<?php echo $produto8["Id"]; ?>"></td> <td><textar ...

The Google map is missing from view, but the search box is visible

The Google map is not showing, but the search box is visible. I am unsure about what could be causing this issue in my code. I have set the size of the div, so that may not be the reason for it not appearing on the screen. Also, I have not attached the CSS ...

"Converting an array within a single object into an object: step-by-step

After retrieving a single row of record from MySQL using Node.js and Express.js, I found that the result was returned as an array inside an object. Here is the output of the result: [ { "user_id": 1, "name": "Aravinth", "email ...

Updating model values while dragging with Angular Dragular

Currently, I am experimenting with dragula and its newer version, dragular, on some sample projects. One specific dilemma I am facing involves the implementation of drag and drop functionality in an Angular project. My query pertains to utilizing a list o ...

When utilizing JSON data in node.js, the .find() method may return undefined

I am currently working on a node server and my goal is to display JSON data when a specific ID is clicked. I have configured a dynamic URL that will retrieve the data of the clicked video using parameters and then compare it with the data in the JSON file ...

Which is more efficient for selecting population data: using Ajax to request a JSON Object or echoing HTML directly?

Currently, I am faced with a dilemma regarding populating a <select> element with values obtained from an Ajax call. The question that perplexes me is whether to have the Ajax response return a well-structured JSON object comprising keys and values o ...

Guidelines on populating a Vue array with data fetched from an Axios request

The v-breadcrumbs component is used to display data from the breadcrumbs array, which works seamlessly with static data. <v-row> <!-- Breadcrumbs --> <v-col class="d-flex"> <v-breadcrumbs :items="breadcrumbs"></v ...

Leveraging a JSON file as a data repository for chart.js

I am struggling to incorporate JSON values into a bar chart. I have successfully logged the JSON data in the console, but I'm unsure how to include it in the data property for the chart. Below is the source JSON... {time: "2016-07-03T21:29:57.987Z" ...

The Bootstrap navbar stubbornly refuses to hide after being clicked on

Is there a way to adjust the data-offset-top for mobile view? Additionally, I am having trouble hiding the menu when clicking on a link. I have tried some code from stackoverflow without success. Can someone please assist with this issue: <nav class= ...

Ensure that there are no empty values within a nested object

Here is a data array structure that I am working with: let data = [{ id: 1, name: '', children: [{ id: 11, name: '', children: [] }, { id: 12, name: '', children: [{ id: 121, name: '', children: [] }, { id: 122, name ...

Generating a dynamic drop-down menu in Django using database values

My goal is to create a Django app that includes dynamic drop-down lists for vehicle makes and models. When selecting a specific make, the models list should update to display only the models that fall under that make. I believe this can be achieved using j ...

When attempting to implement sound on hover with an <a attribute containing an image>, the functionality is not functioning as expected

Is there a way to make a sound play only once when hovering over a list item that contains an image? Here is the HTML and JavaScript code I am using: function playclip() { var audio = document.getElementsByTagName("audio")[0]; audio.play(); } <ul ...

Text is misaligned with the cursor position

I've created an HTML file and implemented a typewriter-like animation using typed.js. Here's the code snippet: var typed = new Typed('#typed', { stringsElement: '#typed-strings', smartBackspace:true, ...

Arrange pictures into an array and showcase them

I'm encountering some difficulties with organizing my images in an array and displaying them in a canvas element. Javascript code snippet canvas = document.getElementById('slideshow'); canvasContent = canvas.getContext('2d'); va ...

Attempting to retrieve key-value pairs from a nested JSON array

I am attempting to extract values along with their corresponding key names from a nested JSON array resData =[ { _index: 'web', _type: 'event', _id: 'web+0+93', _score: null, _source: { 'os-nam ...

Unable to call upon JavaScript code from an external file

Just starting out with Spring and JavaScript! I've put together a JSP file https://i.sstatic.net/XemJ5.png In my first.js, you'll find the following method: function firstmethod() { window.alert("Enter a New Number"); return true; } H ...