search through an object to find specific data

Here is a JavaScript object that I have:

var data = 
{
  "type": [
    "car",
    "bike"
  ],
  "wheels": [
    "4",
    "2"
  ],
  "open": [
    "Jan",
    "Jan"
  ],
  "wheel_press": [
    "35",
    "19"
  ],
  "max-weight": [
    "4000",
    "8"
  ],
  "transition_plan": [
    "",
    null
  ],
  "number_of_occurence": [
    5696,
    976
  ],
  "model": [
    "sedan",
    "street"

}

I am trying to filter the object based on a specific key to get only the corresponding values for that key. Unfortunately, I haven't been able to find a similar question on StackOverflow.

I attempted to use this code snippet:

data.filter(type === 'car')

However, I encountered the following error:

.filter is not a function

The expected output should be as follows: If I filter on type === 'car', it should only display:

{
  "type": [
    "car"
  ],
  "wheels": [
    "4"
  ],
  "open": [
    "Jan"
  ],
  "wheel_press": [
    "35"
  ],
  "max-weight": [
    "4000"
  ],
  "transition_plan": [
    ""
  ],
  "number_of_occurence": [
    5696
  ],
  "model": [
    "sedan"

}

Answer №1

To retrieve the index of a specific value within a property, you can create a function that utilizes Object.fromEntries(), Object.keys(), and Array.map(). This function will generate a new object based on the following example:

var data={type:["car","bike"],wheels:["4","2"],open:["Jan","Jan"],wheel_press:["35","19"],"max-weight":["4000","8"],transition_plan:["",null],number_of_occurence:[5696,976],model:["sedan","street"]};


const getFilteredObject = (property, value) => {
  const index = data[property].indexOf(value)
  
  return Object.fromEntries(Object.keys(data).map(key => ([key, data[key][index]])))
}

const filteredObject = getFilteredObject('type','car');

console.log(filteredObject)

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

CRITICAL ERROR: CALL_AND_RETRY_LAST Memory allocation failed - JavaScript heap exhausted

I am experiencing issues when trying to search using npm: npm search material However, I keep getting this error message: npm WARN Building the local index for the first time, please be patient FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaSc ...

Is it possible to implement the splice() method within a forEach loop in Vue for mutation

Hey there! I'm looking for a more efficient way to replace objects that match a specific index with my response data. Currently, I'm attempting to use the splice() method within a forEach() loop in Vue.js. However, it seems to only remove the obj ...

Using Regular Expressions to eliminate any characters that are not directly adjacent to numbers (beside specific characters)

My function generates a result that looks like this: given output For comparison, consider the example string below: var string = '    111   1   1\n 1111111 1 \n   &nb ...

What causes the disappearance of connecting lines after pushing content into a tab?

I have been using a jquery-connections framework to establish connections between elements on my webpage. However, I encountered an issue where the connectors disappear whenever I insert content inside the Tab. Upon including the following code: <div ...

Guide user to different screen in React Navigation depending on context state

In my project, I have introduced a new state called roleSelected. Initially, the value of this state is set to false, and it is managed within my AuthContext. const [roleSelected, setRoleSelected] = useState(false); The configuration of my stack navigatio ...

Ensure your mobile device is age 13 or over before proceeding

I am developing a project with Next js. Here, I want to render a component if it is a mobile device. However, if I use the isMobileDevice value in jsx, I get the errors below. import useTranslation from "next-translate/useTranslation"; import isM ...

Dynamic styles object for React components with inline styles

I have a styles object let styles = { step_div:{ height:'150px', } } I'm trying to display multiple div elements with different colors using React class Layout extends React.Component{ constructor(props) { super(props); ...

VueJs Ellipsis Filter: Enhance Your Texts with

Using Vue.JS, I am dynamically injecting text content into a DOM element. <article>{{ movie.summary }}</article> My goal is to implement an auto-ellipsis filter. Essentially, the code would look like this: <article>{{ movie.summary | e ...

Dealing with Errors When Working with Angular Promises

Currently, I am in the process of mastering promises within Angular. In my code snippet, I have two "GET" requests that I need to execute sequentially. Everything is functioning properly, but I'm unsure about how to handle errors in this scenario. If ...

Trigger a function when a button is clicked

This is an ongoing project that includes a calculator and other features. Right now, I am working on a functionality where when you input a number into the calculator results and press "+", it should trigger onClick to check if the input was an integer o ...

An issue with the JSON format encountered in the D3 pack layout

I am completely new to d3 and have only been learning it for the past 3 days. I attempted to create a pack layout, but I encountered an issue where I couldn't call the translate (or transform) function based on the data in an external json file. The s ...

The close button is not functioning properly

I created a script to close my div element by clicking on the 'x' icon, but instead of deleting the div only, the whole page gets deleted. I'm not sure where I went wrong, can anyone help me? HTML <div class="note"> <span id ...

How can I refresh the node server during runtime?

In my Express server, I am currently working on defining an endpoint that triggers a restart of the server automatically during runtime. Here is a snippet showcasing how this could be implemented: var express = require('express') var app = expre ...

Exploring the world of JSON and JavaScript data structures

Can someone provide some clarification please? var a = '{"item":"earth", "color":"blue", "weight":920}'; Is the data type of a a string or an array ? var b = JSON.parse(a); What is the data type of b - an object or an array ? ...

Developing an interface that utilizes the values of an enum as keys

Imagine having an enum called status export enum status { PENDING = 'pending', SUCCESS = 'success', FAIL = 'fail' } This enum is used in multiple places and should not be easily replaced. However, other developers migh ...

Modify CSS class if user is using Internet Explorer version 10 or above

I am attempting to modify the CSS of 2 ASP controls using jQuery specifically for users accessing the site with Internet Explorer 10 or 11. This adjustment is necessary because IE10 onwards, conditional comments are no longer supported. My approach to achi ...

When you click on a list of links, a stylish image gallery will appear using fancybox

Can anyone lend a hand with this? I would greatly appreciate any assistance CSS <a id="fancybox" href="javascript:;">Gallery 1</a> <br /> <a id="fancybox" href="javascript:;">Gallery 2</a> <br /> <a id="fancybox" hr ...

Executing AJAX calls within a forEach loop

I'm facing a challenge with a function that carries out a foreach loop on a list of views and needs to make an AJAX request for each view within the loop. Upon receiving the results in the success callback, it checks if a specific ID is returned and, ...

In my development environment, the page does not have scroll functionality, but in the production environment, it is scrollable

Whenever I open a table or any other element with overflowing content, I encounter an issue with the scrolling bar. Even though the CSS includes overflow-y: scroll;, the scroll bar on the right remains in gray and does not allow me to scroll down when the ...

performing functions concurrently within angularjs

I am currently utilizing angularjs 1.0 within my application. There is a dropdown on my cshtml page <select tabindex="2" id="Employee" ng-model="models.SelectedEmployee" ng-change="changeEmployee()" disabled="disabled" class="Answer" size="6"> < ...