Filtering nested object properties by value using Java Script

I am seeking assistance in filtering nested Objects by property values, with a specific requirement involving values stored in an array. Despite previous similar inquiries, I have yet to find a solution tailored to cases like mine.

In reviewing the code snippet provided, my objective is to filter objects based on specific tags. Specifically, I aim to retrieve objects that contain both "a" and "b" within their tags array.

const input1 = {
    "0":{
        "id":"01",
        "name":"item_01",
        "tags":["a","b"],
    },
    "1":{
        "id":"02",
        "name":"item_02",
        "tags":["a","c","d"],
    },
    "2":{
        "id":"03",
        "name":"item_03",
        "tags":["a","b","f"],
    }
}
 
function search(input, key) {
   return Object.values(input).filter(({ tags }) => tags === key);
}

console.log(search(input1, "a"));

The desired outcome consists of the following:

{
    "0":{
        "id":"01",
        "name":"item_01",
        "tags":["a","b"],
    },
    "2":{
        "id":"03",
        "name":"item_03",
        "tags":["a","b","f"],
    }
}

Your help is greatly appreciated!

Answer №1

In order to maintain the object structure, it is recommended to utilize Object.entries instead of Object.values. To convert back to an object type, you can employ Object.fromEntries:

Object.fromEntries(Object.entries(input).filter(...))

If you need it to function for multiple keys, combine every with includes as a predicate:

keys.every(key => tags.includes(key))

const input1 = {
    "0":{
        "id":"01",
        "name":"item_01",
        "tags":["a","b"],
    },
    "1":{
        "id":"02",
        "name":"item_02",
        "tags":["a","c","d"],
    },
    "2":{
        "id":"03",
        "name":"item_03",
        "tags":["a","b","f"],
    }
}
 
function search(input, keys) {
   return Object.fromEntries(
   Object.entries(input).filter(([, { tags }]) => keys.every(key => tags.includes(key)))
   )
   
}

console.log(search(input1, ["a", "b"]));

Answer №2

const findItem = (data, searchTerm) => {
  return Object.values(data).filter(item => item.tags.includes(searchTerm));
}

Answer №3

If you want to extract the key-value pairs from an object and filter them based on a specific condition, you can utilize the Object.entries method to convert them into an array of arrays. Then, you can apply the filter function to eliminate elements that do not meet the specified criteria defined in the key array. Lastly, you can use the reduce method to consolidate the filtered values into a single object.

const input1 = {
  "0": {
    id: "01",
    name: "item_01",
    tags: ["a", "b"],
  },
  "1": {
    id: "02",
    name: "item_02",
    tags: ["a", "c", "d"],
  },
  "2": {
    id: "03",
    name: "item_03",
    tags: ["a", "b", "f"],
  },
};

function search(input, key) {
  return Object.entries(input)
    .filter(([, v]) => key.every((ks) => v.tags.includes(ks)))
    .reduce((acc, [k, v]) => {
      acc[k] = v;
      return acc;
    }, {});
}

console.log(search(input1, ["a", "b"]));

Answer №4

function searchTags(input, tagsToFind) {
  return Object.values(input).filter(inputItem => {
    tagsToFind = Array.isArray(tagsToFind) ? tagsToFind : [tagsToFind];
    let tagFound = false;
    for (const key in tagsToFind) {
      if (Object.prototype.hasOwnProperty.call(tagsToFind, key)) {
        const element = tagsToFind[key];
        if (inputItem.tags.indexOf(element) === -1) {
          tagFound = false;
          break;
        } else {
          tagFound = true;
        }
      }
    }

    return tagFound;
  })
}

}

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

Issue encountered in Wicket Ajax Error Log: ERROR: The listener for the "click" event cannot be bound to the "AjaxCheckBox" element as it is not present in the Document Object Model (DOM)

When running my program, I am trying to dynamically add Panels to the main page and utilize "setVisible(boolean)" functionality. However, I am encountering an error: ERROR: Cannot bind a listener for event "click" on element "institutCheck7" because the ...

Activate the submission button on AngularJS once a correctly formatted email is provided

Currently working on an AngularJS demo to better understand its functionalities. The next task on my list is to enable the submit button only when a valid email address is entered. I'm seeking guidance on how to approach this and what concepts I need ...

In order to determine if components linked from anchor elements are visible on the screen in Next.js, a thorough examination of the components

Currently, I am in the process of developing my own single-page website using Next.js and Typescript. The site consists of two sections: one (component 1) displaying my name and three anchor elements with a 'sticky' setting for easy navigation, a ...

Determine the position of an item within an array in order to find the matching object in a separate array

I am currently working with two arrays. One array contains names and the other consists of strings labeled as "Yes" or "No". The index position for each name in the "name" array corresponds to the same index position in the "Yes/No" array. For instance: ...

encase a function with javascript

let myString = "I am creating a program."; //function to calculate number of letters const letterCount = (str) => str.length; //function to calculate number of words const wordCount = (str) => str.split(" ").length; //function ...

Searching for Bluetooth devices using React Native

In my project, I am working on scanning HM-10 BLE with a react-native app. To achieve this, I referred to the example provided in Scanning for Bluetooth devices with React Native. So far, the library seems to be successfully installed without any errors du ...

Issues with synchronizing Firebase and Node.js?

https://i.stack.imgur.com/3fwRO.png Here is the code snippet I used in my Node.js application: for(var v in sna.val()){ console.log("each "+va); console.log(v); var fourthRef = ref.child(val+'/reservation/&apos ...

What is the best way to format 100K to appear as 100,000?

function formatNumberWithCommas(num) { return num >= 1000 ? `${Number.parseFloat((num).toFixed(3))}` : num; } ...

Is it possible to receive an Infinite value from the Vector.project() function in Three.js

Could someone please explain why I am getting {x:Infinity, y:-Infinity, z:-Infinity} as my position values {x:0.50516157, y:-0.62950189, z:0} when attempting to project my position vector onto the camera? I have come across a similar issue on Stack Overf ...

State change shows the previous and current values simultaneously

I've been working on updating the values of initUsers on the DOM. The initial state values work fine, but when I try to update initUsers, it displays different values than expected. Essentially, entriesNum receives a number as an event and changes th ...

Connect to dynamically generated div on separate page

I am facing an issue with my navigation bar drop down menu that displays event titles fetched from the database. I want users to be able to click on a specific event and have the page scroll to the dynamically generated content for that event. However, it ...

Is my implementation of Model and Views in backbone.js accurate?

I'm new to backbone.js and I've just created my first page. I'm curious to know if I'm headed in the right direction with my approach (if there even is a "correct" way in software development). Is there a way to automatically bind mode ...

Attempted to execute my testing script with mocha, however encountered a "Reference Error: beforeEach is not defined" issue

While running my test script for a todo app in node.js using Mocha, I encountered a reference error stating that "beforeEach is not defined". The code snippet causing the issue is shown below: const {app} = require('./../server'); const {Todo} ...

How to prevent all boxes in jQuery from sliding up at the same time

I am encountering an issue with 36 boxes where, upon hovering over the title, the hidden text below it should slide up. However, all 36 boxes are sliding up simultaneously instead of just the one being hovered over. Below is the script I am currently using ...

What initiates the call for CSS?

During his instructional video, the creator visits the CodeIgniter website at . When he initially arrives at the site (at 1:32), it appears somewhat odd, almost as if it lacks CSS styling. However, after refreshing the page (1:37), it displays properly. ...

I encountered an error with the array [3,5,0,3,4]. How is it possible for this array to contain a 132 pattern?

Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] where i is less than j and j is less than k, and nums[i] is less than nums[k] which is less than nums[j]. Verify if there exists a 132 pattern ...

The issue with scaling SVG files imported via Babel in Next.js is still

I've been attempting to decrease the size of my SVG icon in my next.js project. To import SVGs into my project, I included a file called .babelrc with the following: { "presets": ["next/babel"], "plugins": [" ...

The iframe content is not updating despite using jQuery

On this site , the following code is present: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <iframe style="position: absolute; top: 0; left: 0; height: 100%; width: 100%" src="blank.html"></iframe ...

Using JavaScript with Selenium, you can easily clear the input field and send

Here is a question input field. When clicked on, the h3 element with the name will disappear and the input tag will appear for entry of a new name. <td style="width:92%;"> <h3 id="question_tex ...

What is the technique for extracting data from a Firebase application after a user has successfully logged in?

I'm currently facing an issue with my website's forum, which is integrated with Firebase for storing forum posts and user login information. The challenge I'm encountering involves retrieving data from the logged-in user's child in orde ...