skip to Main Content

I have a array like this

[{"name":"Typical value Sydney (SUA) Houses", "value":"Bar" },
 {"name":"Days on market Sydney (SUA) Houses", "value":"Bar" },
 {"name":"Typical value Melbourne (SUA) Houses", "value":"Line" },
 {"name":"Days on market Brisbane (SUA) Houses", "value":"Bar" }]

I have another variable that I receive the name "Days on market Sydney (SUA) Houses"
I want to find the the name in the array and get the corresponded value like "Bar"

how do I achieve this in javascript

    for (var j = 0; j < arr.length; j++){
        if (arr[j].name == seri){
             value= arr[j].value;
             return true;
        }}

it is not going into the if condition .

2

Answers


  1. You can simple use the Array.find method in JavaScript.

    const temp = [
      { name: "Typical value Sydney (SUA) Houses", value: "Bar" },
      { name: "Days on market Sydney (SUA) Houses", value: "Bar" },
      { name: "Typical value Melbourne (SUA) Houses", value: "Line" },
      { name: "Days on market Brisbane (SUA) Houses", value: "Bar" },
    ];
    
    const toFind = "Days on market Sydney (SUA) Houses";
    const ans = temp.find((el) => el.name === toFind);
    console.log(ans);
    console.log(ans?.value) //To get the value
    Login or Signup to reply.
  2. via Array.prototype.find(), then can search for a specific object in the array

    var array=[{name:"Typical value Sydney (SUA) Houses",value:"Bar"},{name:"Days on market Sydney (SUA) Houses",value:"Bar"},{name:"Typical value Melbourne (SUA) Houses",value:"Line"},{name:"Days on market Brisbane (SUA) Houses",value:"Bar"}];
        
      var b = array.find(function(a) {
        return "Days on market Sydney (SUA) Houses" === a.name;
      });
    
      // B now have the object with the corresponding name and value
    
      console.log(b.value);  // output will be Bar
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search