Retrieving a value from an object in an array of objects based on the condition of another object property

Is there a way to save the value of naziv.value in var naziv within the find method without declaring another variable?

var naziv = obj.find(c => c.name === "naziv");
console.log(naziv)

The current output is test when using console.log(naziv.value), but I would prefer just using console.log(naziv).

var obj = [{
    name: "naziv",
    value: "test"
  },
  {
    name: "zzz",
    value: "xxx"
  }
]

var naziv = obj.find(c => c.name === "naziv");
console.log(naziv.value)

EDIT: And also, if the name is the same, how can we create an array of values? For example:

var obj = [{
    name: "naziv",
    value: "test"
  },
  {
    name: "zzz",
    value: "xxx"
  },
  {
    name: "Telefon[]",
    value: "tel1"
  }, {
    name: "Telefon[]",
    value: "tel2"
  }
]

var naziv = obj.find(c => c.name === "Telefon[]");
console.log(naziv.value)

The expected result is: [tel1,tel2]

Answer №1

To implement de-structuring, try using

const {result:brand} = items.filter(item => item.type === "brand");

Answer №2

If you're looking to gather multiple values in an array, this is one approach

var obj = [{name:"naziv",value:"test"},{name:"zzz",value:"xxx"},{name:"Telefon[]",value:"tel1"},{name:"Telefon[]",value:"tel2"}]

var naziv = obj.filter(c => c.name === "Telefon[]").map(res => res.value);
console.log(naziv)

Similarly, if a single value is expected as the output, the following method can be used. Here, Optional Chaining is utilized

var obj = [{name:"naziv",value:"test"},{name:"zzz",value:"xxx"},{name:"Telefon[]",value:"tel1"}]

var naziv = obj.find(c => c.name === "Telefon[]")?.value;
console.log(naziv)

In cases where older browser versions do not support Optional Chaining, another alternative is provided below

var obj = [{name: "naziv",value: "test"},{name: "zzz",value: "xxx"},{name: "Telefon[]",value: "tel1"}]

var naziv = (obj.find(c => c.name === "Telefon[]") || {}).value;
console.log(naziv)

var notFound = (obj.find(c => c.name === "not_found") || {}).value;
console.log(notFound);

Answer №3

let items = [{
    title: "apple",
    price: "$1"
  },
  {
    title: "banana",
    price: "$0.50"
  },
  {
    title: "apple",
    price: "$1.25"
  }
]

let apples = items.filter(item => item.title === 'apple').map(item => item.price)
console.log(apples)

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

transforming basic pagination using javascript to jquery implementation

I have a straightforward pagination code written in raw JavaScript. function UpdatePage(e){ if(busy == 0) { switch(e) { case "Next": page = p+1; p++; break; ca ...

Is the array_unique function malfunctioning in PHP?

I have a table stored in my MySQL database: pageid | text -----------+---------- 1 | test -----------+---------- 2 | example -----------+---------- 3 | another -----------+---------- 1 | example1 There is also this ...

Unable to generate any output from the link when using 'react-router-dom'

Having trouble integrating a NavBar into my React app.js file. The Route files are loading correctly, but the Links set in the NavBar component aren't showing up on the page. Here is the code for NavBar: import React from 'react'; import { ...

Error in Stripe.js: Unable to access the property 'stripeToken' because it is undefined

I'm currently in the process of integrating stripe.js into a web application that I'm developing. However, I encountered the following error: Cannot read property 'stripeToken' of undefined Although the client-side is setting the hidd ...

What is the method for adding npm dependencies that are not included in the package.json file during installation?

I am facing an issue with running npm install. I need to install all the dependencies used in my project. In my project files, there are various instances like const mongo=require('mongoose') and const morgan=require('morgan'), even tho ...

"Exploring the world of Typescript's return statements and the

I'm currently grappling with a design dilemma in typescript. Within my controller, I perform a validation process that can either return a 422 response, which ends the thread, or a validated data object that needs to be utilized further. Here's a ...

What could be the issue with this particular Ajax script?

I am facing an issue with this JavaScript code - it runs smoothly in Chrome and IE, but encounters a problem in Firefox. I need assistance in identifying the issue. Can anyone help? <script> function checkGurantee() { var gurantee = document.get ...

The process of retrieving the initial character from every element in an array is not functional

I am attempting to retrieve the first character from each element within an array using Javascript. I want to extract the first characters like 1, 4, 7, 2, 5, and 8 from the elements '123', '456', '789', '234', &apos ...

What are the methods for accessing data-bind keys and value observables in knockout.js through elements?

I am looking to retrieve data-bind keys and values observable through an element. <select id="selector" data-bind="options: selectOptions, value: selectedValue"></select> var ViewModel = { selectOptions: ko.observableArray([...]), selec ...

How to Generate a 3D Array of Double Values in Swift 5 and Send it to a C Function

I am facing a challenge with calling a legacy C function (from Swift) that requires a 3D array of Doubles as an argument. As I transition a substantial codebase from ObjC and C to Swift, which involves intricate astronomical calculations, I have encountere ...

Is it possible to execute in a specific context using npm?

I am seeking to execute npm scripts that are executable by VuePress. For instance, I have VuePress installed and would like to run the command vuepress eject. Although I can access vuepress in my scripts, there is no specific script for eject: "scr ...

Can I restrict access to all routes except one in vue-router? Is this a safe practice? Should I explore alternative methods for achieving this?

I am looking to create an online exam consisting of 5 pages, each with a countdown timer set at 120 seconds and 4 questions on each page. Once the timer runs out, users will be automatically redirected to the next page, or they can manually click the "next ...

Issue: React cannot render objects directly. Received an object of objects instead of an array of objects

As someone who is fairly new to React, I am in the process of fetching data from my Jobly backend. Upon setting the company data received from the backend, I noticed that company.jobs is interpreted as an array of objects. However, when I attempted to assi ...

The mention of 'subscript' within the wordEquiv[i] member is unclear and puzzling

let num: UInt16 = 20_168 var numberString = String(num) var wordEquiv = ["1": "One", "2": "Two", "3": "Three", "4": "Four", "5": "Five", "6": "Six", "7": "Seven", "8": "Eight", "9": "Nine"] for char in numberString { if let word = wordEquiv[String(cha ...

`Making adjustments to specific text on an HTML page prior to its presentation`

I am looking for a way to conceal specific text on any HTML page before it is shown. After some experimentation with Greasemonkey, I attempted the following approach: var html = document.body.innerHTML; html = html.replace( /some pattern/g, '???&apo ...

How can I create a parent-child tree structure in Ruby using only arrays, without relying on external gems

I am working with an array that contains a list of items in the following format: arr = [ {:id=>1, :title=>"A", :parent_id=>nil}, {:id=>2, :title=>"B", :parent_id=>nil}, {:id=>3, :title=>"A1", :parent_id=> ...

What is the value of x in the equation 2 raised to the power of x equals 800

Similar Question: What is the reverse of Math.pow in JavaScript? 2^x=i If i is given, how can we determine x using Javascript? ...

What is the best way to combine 2 javascript objects to create a JSON structure without any nested levels?

I am having an issue with my mock server setup. I am using npm faker to generate random data, and then trying to transfer that data to another JavaScript file. My goal is to have a JSON structure like the following: { 0: varOne: 'value' ...

What is the best way to add a new div below a specific div without disrupting the existing layout of other elements on the page?

Is there a way to create a new div that appears below a specific div on a webpage, but is displayed above all other elements without affecting their positioning? Here is an example: --------------------------------------------- | | ...

I'm trying to implement a command in my bot that displays the number of Discord members, but I keep encountering an error

I've encountered an issue with the discord.js v13 member count command. Despite seeking help in various Discord servers, I haven't received any assistance. If anyone could offer their expertise, it would be greatly appreciated. const Discord = re ...