Tips for sorting through an array containing various types of data

I'm dealing with an array structured like this:

const AllFiles = [

    {name: "ExistingFile1", mimetype: "image/jpg", size: "500"},

    [ 
     File, // This is the New File itself (see File API)
     {name: "NewFile1", mimetype: "video/mp4", size: "9000"}
    ],

    {name: "ExistingFile2", mimetype: "video/mp4", size: "4000"},

    [ 
     File, // This is the New File itself (see File API)
     {name: "NewFile2", mimetype: "image/jpg", size: "500"}
    ],

 ]

The AllFiles array includes a mix of objects and arrays.

I am trying to filter the AllFiles array to only retrieve items where the mimetype begins with "image/".

This is what I started with:

const FilteredFiles = AllFiles.filter((FileItem, index) => FileItem.mimetype.startsWith("image/"))

The issue is that it only checks for the mimetype in top level objects. It does not check deeper where a New File has the mimetype within a second level object inside an array.

To access the mimetype of existing files you must use: FileItem[0].mimetype

However, to access the mimetype for new files you need to use: FileItem[0][1].mimetype

Due to this inconsistency, I am struggling to filter the AllFiles array. Is there a way to solve this?

Answer №1

If you want to achieve a concise solution, consider using the ?? operator:

const AllFiles = [{name:"ExistingFile1",mimetype:"image/jpg",size:"500"},["FILE",{name:"NewFile1",mimetype:"video/mp4",size:"9000"}],{name:"ExistingFile2",mimetype:"video/mp4",size:"4000"},["FILE",{name:"NewFile2",mimetype:"image/jpg",size:"500"}]];
 
const result = AllFiles.filter(f => (f[1] ?? f).mimetype.startsWith('image'));

result.forEach(r => console.log(JSON.stringify(r)));

Answer №2

If you're looking for a straightforward way to retrieve data from an array of entities, one simple approach is to first check if each entity has the mimetype property. If it does, you can access the data directly. However, if the property is not present, you can assume that the entity is an array and extract the information from the second element instead.

const File = "foo", AllFiles = [{name:"ExistingFile1",mimetype:"image/jpg",size:"500"},["foo",{name:"NewFile1",mimetype:"video/mp4",size:"9000"}],{name:"ExistingFile2",mimetype:"video/mp4",size:"4000"},["foo",{name:"NewFile2",mimetype:"image/jpg",size:"500"}]];

const filteredFiles = AllFiles.filter(entity => {
  const obj = entity.hasOwnProperty('mimetype') ? entity : entity[1];
  return obj.mimetype.startsWith("image/");
});

console.log(filteredFiles);

It's important to note that this example is just for illustrative purposes. In a real-world scenario, it would be wise to implement additional checks to ensure the accuracy and reliability of the data retrieval process. Nevertheless, the provided code snippet offers a basic template to work with.

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

Attempting to format a number using a computed property and .toLocaleString() fails to execute

I am facing an issue with the formatting of a number displayed in a <p></p> element. The number is coming from a range input element that is bound to an amount data property using v-model. Even though I have a computed property to format the nu ...

How to access the CSS and JS files in the vendor folder using linemanjs

Currently, I am in the process of developing a web application utilizing linemanjs. However, I have encountered an issue where the vendor css and js files are not being referenced correctly when explicitly included. I would appreciate any guidance on what ...

Is the div empty? Maybe jQuery knows the answer

I currently have a <div id="slideshow"> element on my website. This div is fully populated in the index.php file, but empty in all other pages (since it's a Joomla module). When the div is full, everything works fine. However, when it's emp ...

Using a variable to retrieve results from an array leads to an undefined outcome

I am encountering an issue with accessing arrays returned from a `GET` response. The names of these arrays may vary depending on the request, so I have a variable that specifies which array to use. Unfortunately, I keep receiving 'undefined'. Fo ...

Why are the elements not found by their id when I check them, even though they were created dynamically using an ajax-generated form with php-inserted values through a

How can I prepopulate form fields displayed in a modal view using jQuery after retrieving the form HTML with an AJAX query? I am trying to set the values through a JavaScript function that retrieves PHP-generated values via document.getElementById. However ...

Getting data from a response in Express.js involves using the built-in methods provided by

I am a beginner at Node.js and I'm currently experimenting with client-server communication. Below are the codes I've been working on: server: app.post('/zsa', (req, res) => { res.send("zsamo"); }); client: fetch(&qu ...

Concealing the toolbars on iOS 7 with the overlay technique

After researching on Stack Overflow and Google, I have been trying to find a reliable method to hide the toolbars on iOS 7 since the old scroll trick is no longer effective. I came across this resource: I attempted the following code: <!doctype html& ...

Retrieve items from a JSON file using Ionic framework's $http.get method

Issue with Console: SyntaxError: Unexpected token { in JSON at position 119 Xcode controller: str="http://www.website.com/user-orders.php?e="+$scope.useremail; $http.get(str) .success(function (response){ $scope.user_orders = response; ses ...

Execute the Angular filter again when there is a change in the scope

I am currently working on an application where Users have the ability to switch between kilometers and miles for unit distances. To handle this, I created a custom filter that converts the distances accordingly: app.filter('distance', function() ...

Using AngularJS to showcase nested JSON arrays

Just starting out with angularjs and seeking some guidance. Our angular front-end is connected to a REST API delivering JSON data like this: [ { "category_id":"1", "category_name":"dog", "subcategories":[ { ...

I'm wondering why my positive numbers aren't displayed in green and negative numbers in red

I am currently working on a commodities quotes widget. I have already set up the 'Current' and '24-hour' divs, but I'm facing an issue where positive values are not displaying in green and negatives in red as intended. I have check ...

Tips for integrating external JavaScript libraries and stylesheets into a widget

I am currently working on developing a custom Javascript widget that requires users to insert specific lines of code into their web pages. This code will then dynamically add an externally hosted javascript file, allowing me to inject HTML content onto the ...

Is the input field not properly centered on the page?

Can someone explain why the input field is not aligning in the center? I am new to web development and need some assistance. <input type="text" id="search_bar" class="form-control" placeholder="Search" align="center"> In my CSS, I've ...

What could be causing the malfunction of removeEventListener in my Nuxt application?

Whenever a search result is displayed on my app, the component below renders and checks if the user scrolling is at the bottom of the page. Initially, the code works fine, but I encounter an error when returning to the page after navigating away and scro ...

Effortlessly saving money with just one click

I have a search text box where the search result is displayed in a graph and then saved in a database. However, I am facing an issue where the data is being saved multiple times - first time saves properly, second time saves twice, third time three times, ...

Guide on comparing values in a MongoDB document field using NodeJS

I am currently utilizing Nodejs and mongoDB as the backend service for my application. The database structure is outlined below: { { _id:"1" Name:"Roy" Place:"Null" }, { _id:"2" Name:"john" Place:"Ajmer" } } My object ...

Issues with jQuery Progress Bar Functionality

As a beginner in jQuery, I am currently working on creating an interactive progress bar using jQuery. My goal is to provide a set of checkboxes on a webpage so that when a visitor checks or unchecks a checkbox, the value displayed on the progress bar will ...

VueJS and Vite: Encountering an unexpected character '�' while attempting to import files that are not JavaScript. Keep in mind that plugins are required for importing such files

I'm puzzled by the error message I'm receiving: [commonjs--resolver] Unexpected character '�' (Note that you need plugins to import files that are not JavaScript) file: /..../..../WebProjects/..../ProjectName/node_modules/fsevents/fse ...

Optimizing Performance by Managing Data Loading in JavaScript Frameworks

I am new to JavaScript frameworks like React and Vue, and I have a question about their performance. Do websites built with React or Vue load all data at once? For example, if I have a page with many pictures, are they loaded when the component is used or ...

How can errors for assets on a Vue build be disregarded?

In the process of developing a Vue project that involves static files, I have configured the following in my package.json for local serving: { ... "eslintConfig": { ... "ignorePatterns": [ "**/vendor/*.js" ...