Efficiently transferring property values

In my current code, I have functions that retrieve specific properties from an object within an array.

Since each object in the array has multiple properties, I find myself using separate functions to extract different properties. This approach is not efficient and there must be a better way to accomplish this task.

var fiftyplanets = [{
    "Hostname": "11 Com",
    "Distance [pc]": 110.62,
    "Effective Temperature [K]": 4742,
    "Date of Last Update": "5/14/2014"
}];

function findProperty(hostname, property) {
    function search(am, im) {
        if (am.Hostname === hostname) {
            index = im;
            return true;
        }
    }

    var index;
    if (fiftyplanets.some(search)) {
        return fiftyplanets[index][property];
    }
}

var name = value;
var result = fiftyplanets.indexOf(name);
var distance = findProperty(name, 'Distance [pc]');
var temperature = findProperty(name, 'Effective Temperature [K]');

I am looking for a more efficient way to write a single function that can search for specific properties within the objects in the array. Is there a better approach to achieve this?

Answer №1

It may not be exactly what you're searching for, but this eliminates redundant code and consolidates the search into a single function.

var fiftyplanets = [{
    "Hostname": "11 Com",
    "DistancePc": 110.62,
    "effectiveTemperatureK": 4742,
    "dateOfLastUpdate": "5/14/2014"
}];

function getInfo(info, hostname ) {
    function search(am, im) {
        if (am.Hostname === hostname) {
            index = im;
            return true;
        }
    }

    var index;
    if (fiftyplanets.some(search)) {
        return fiftyplanets[index][info];
    }
}

var name = value;
var resullt = fiftyplanets.indexOf(name);
var dist = getInfo('DistancePc', name);

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

Learn the best practices for incorporating jQuery and other JavaScript libraries in your Angular2 projects

Is it possible to integrate a demo showcasing Bootstrap carousel with CSS3 animations in Angular2 using HTML, CSS, and JS? I have created my own implementation in Plunker with Angular2, but I am facing issues with the animated inner content of the carousel ...

Displaying Spinner and Component Simultaneously in React when State Changes with useEffect

Incorporating conditional rendering to display the spinner during the initial API call is crucial. Additionally, when the date changes in the dependency array of the useEffect, it triggers another API call. Question: If the data retrieval process is inco ...

Steps for deactivating jQuery slider control until radio button is selected:

Looking to deactivate the operation of jQuery UI sliders until a radio button is selected. Despite my efforts, I have been unsuccessful in achieving this task and could use some guidance. For reference, here is a link to the code: http://jsfiddle.net/nlem3 ...

How can I switch out an item within FabricJS?

In order to incorporate undo and redo functionality, I have created an array named "history" that stores the most recent changes triggered by canvas.on() events. Displaying console.log: History: (3) […] ​ 0: Object { target: {…} } //initial object ...

Utilizing a static method from a Class imported from a Node.js module

One puzzling question arises: How can we reference other static methods from within a static method of a class exported from a NodeJS module? Let's consider the following scenario. We have two modules: test1.js var Parent = class { static smetho ...

Automate CSS slideshow playback using JavaScript

Using only CSS, I created a basic slideshow where the margin of the element changes upon radio button click to display the desired slide. You can view the functionality in the code snippet below. Additionally, I implemented auto play for this slideshow usi ...

Looking for search suggestion functionalities in an HTML input field

I am currently working on a website project and have a database filled with recipes to support it. The issue I am facing is related to the search feature on my webpage. At the top of the page, there is a textarea where users can input their search queries ...

Displaying an error page instead of the error message when a backend or template engine error occurs

Whenever a template engine error occurs, it is displayed on the webpage. I am looking to implement a functionality where if our server is running in production mode, an error page will be shown instead of displaying our server's error directly. The m ...

Having difficulty implementing a hover event on a sibling element of a target using either the duration parameter in jQuery UI or CSS

My objective is to alter the background color of an element and one of its higher siblings in the DOM but within the same parent upon hover. While I successfully used CSS transition to change the first element, I encountered difficulty getting the sibling ...

Tips for showing the chart title and subtitle using "vue-google-charts" library by devstark: Where to position them - top or bottom?

Utilizing the resource available at https://www.npmjs.com/package/vue-google-charts The title is not being displayed on the chart. Is there a way to show it either above or below the chart? I attempted adding "display=true" with the option "title" and fo ...

The .keypress() function isn't behaving as expected

I've encountered a coding dilemma. Below is the code in question: $(document).ready(function () { var selectedDay = '#selected_day'; $(function () { $("#date").datepicker({ dateFormat: "DD, d M yy", a ...

In JavaScript, efficiently remove specific node types from a tree structure using recursion, while also maintaining and distributing qualified child nodes

Currently, I am working on a recursive function that operates on a JSON tree structure {name, type, [children]}, with the goal of removing nodes of a specific type. However, it is essential that the children of the removed node are reattached to the parent ...

Exploding particles on the HTML5 canvas

I've been working on a particle explosion effect, and while it's functional, I'm encountering some issues with rendering frames. When I trigger multiple explosions rapidly by clicking repeatedly, the animation starts to lag or stutter. Could ...

Code executing twice instead of once in Javascript

Having trouble with a script in my demo below. When I enter "first input", submit, then click on the returned "first input", it alerts once as intended. However, upon refresh, if I enter "first input", submit, then add "second input", submit, and finally c ...

Determine the upcoming Saturday's date by utilizing a stored procedure in Snowflake

Looking for assistance in retrieving the upcoming Saturday date based on a date field in a table using a Snowflake JavaScript stored procedure. Any suggestions would be greatly appreciated. Running the following query in the Snowflake console provides the ...

Using Javascript, dynamically animate the text in the hero unit with fading in and out effects

I currently have a "Hero" unit with the following code: <div class="hero-unit"> <div class="container"> <h1>Dapibus Euismod Mollis</h1> <p>Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis ...

Verifying the existing user in a personalized Ajax form that is used to update a Woocommerce order

Currently, I am developing a form that allows users to update specific order details, such as expenses and the reason for the expense. After updating the order, a JavaScript alert confirms the successful update, and the order's metadata is updated acc ...

What is the best way to utilize a variable across all functions and conditions within an asynchronous function in Node.js?

I need to access the values of k and error both inside and outside a function. Initially, I set k to 0 and error to an empty string, but unexpectedly, the console prints out "executed". var k = 0; var error = ""; const { teamname, event_name, inputcou ...

Adding array elements to a JavaScript object

I find myself in a rather unique predicament that I'm struggling to navigate. I have come across some data structured as follows. Please bear with me if I use any incorrect terminology, as I am relatively new to this. usersByName: { "tester&q ...

Utilize Vue.js to sort by price bracket and category

Hello, I am currently new to working with Vue.js and I am attempting to create two filters - one for price range and the other for genre. Any guidance or assistance would be greatly appreciated. Below is a snippet of my code: ul class="filter-wrapper"&g ...