Querying a JavaScript object

javascript object query language
javascript object to query string
javascript object methods
pass array in query string javascript
javascript object properties
javascript object query library
javascript object to url params
javascript filter object

Given the following three objects, what is an efficient way to return the first object that contains a key-value pair?

var obj = {
  item1: {
    name: 'apple',
    color: 'red'
  },
  item2: {
    name: 'blueberry',
    color: 'blue'
  },
  item3: {
    name: 'cherry',
    color: 'red'
  }
};

var obj2 = {
  collection: [
    {
      item1: {
        name: 'apple',
        color: 'red'
      },
      item2: {
        name: 'blueberry',
        color: 'blue'
      },
      item3: {
        name: 'cherry',
        color: 'red'
      }
    }
  ]
};

var obj3 = {
  items: [
    {
      item1: {
        name: 'apple',
        color: 'red'
      }
    },
    {
      item2: {
        name: 'blueberry',
        color: 'blue'
      },
    },
    {
      item3: {
        name: 'cherry',
        color: 'red'
      }
    }
  ]
};

I would like to get the same results for the following three statements:

getObject(obj, 'color', 'red');
getObject(obj2, 'color', 'red');
getObject(obj3, 'color', 'red');

Output:

{
  name: 'apple',
  color: 'red'
}

Here's what I have so far, but I think it's missing a closure somewhere since it breaks when the function calls itself:

function getObject(arg, key, val) {
  if (typeof arg!=='object') return null;
  switch (Object.prototype.toString.call(arg)) {
    case '[object Array]':
      for (var i=0; i<arg.length; ++i) {
        getObject(arg[i], key, val);
      }
      break;
    case '[object Object]':
      for (var i in arg) {
        if (arg.hasOwnProperty(i)) {
          if (typeof arg[i]==='object') {
            getObject(arg[i], key, val);
          } else {
            if (i===key && arg[i]===val) {
              return arg;
            }
          }
        }
      }
      break;
  }
}

You could use this function, which will also search in more deeply nested data structures.

function getObject(obj, prop, value) {
    if (Object(obj) !== obj) return; // It is not an object
    if (obj[prop] === value) return obj; // Found it
    for (var key in obj) {
        var result = getObject(obj[key], prop, value);
        if (result) return result; // Found it
    }
}

var obj = {item1: {name: 'apple',color: 'red'},item2: {name: 'blueberry',color: 'blue'},item3: {name: 'cherry',color: 'red'}};
var obj2 = {collection: [{item1: {name: 'apple',color: 'red'},item2: {name: 'blueberry',color: 'blue'},item3: {name: 'cherry',color: 'red'}}]};
var obj3 = {items: [{item1: {name: 'apple',color: 'red'}},{item2: {name: 'blueberry',color: 'blue'},},{item3: {name: 'cherry',color: 'red'}}]};

console.log(getObject(obj, 'color', 'red'));
console.log(getObject(obj2, 'color', 'red'));
console.log(getObject(obj3, 'color', 'red'));

simple-object-query, npm install simple-object-query. bower install simple-object-query. Really simple lib to find a deep value in an object. I'll use this source object� Selectors Level 1 Document Object: Return Value: A NodeList object, representing the first element that matches the specified CSS selector(s). If no matches are found, null is returned. Throws a SYNTAX_ERR exception if the specified selector(s) is invalid.

You could use Array#some for a short cut, if the object is found.

function getObject(object, key, value) {
    var result;
    if (!object || typeof object !== 'object') return;
    if (object[key] === value) return object;
    Object.values(object).some(v => result = getObject(v, key, value));
    return result;
}

var obj = { item1: { name: 'apple', color: 'red' }, item2: { name: 'blueberry', color: 'blue' }, item3: { name: 'cherry', color: 'red' } },
    obj2 = { collection: [{ item1: { name: 'apple', color: 'red' }, item2: { name: 'blueberry', color: 'blue' }, item3: { name: 'cherry', color: 'red' } }] },
    obj3 = { items: [{ item1: { name: 'apple', color: 'red' } }, { item2: { name: 'blueberry', color: 'blue' } }, { item3: { name: 'cherry', color: 'red' } }] };

console.log(getObject(obj, 'color', 'red'));
console.log(getObject(obj2, 'color', 'red'));
console.log(getObject(obj3, 'color', 'red'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

JavaScript object basics, Objective: To understand the basic theory behind object-oriented programming, how this relates to JavaScript ("most things are objects"), and� A Parse.Relation behaves similar to an array of Parse.Object for querying purposes, so any query you can do on an array of objects, you can do on a Parse.Relation. Data Types. So far we’ve used values with type String, Number, and Parse.Object. Parse also supports Dates and null.

Your approach within getObject is OK, however, as a general approach, you should transform the array for each all. You can use the function map in order to prepare the array for the finding process.

The function find "finds" the object according to a specific predicate.

This is assuming the indexes are related to the keys -> index i==0 -> items1, and so on.

var obj = {item1: {name: 'apple',color: 'red'},item2: {name: 'blueberry',color: 'blue'},item3: {name: 'cherry',color: 'red'}};
var obj2 = {collection: [{item1: {name: 'apple',color: 'red'},item2: {name: 'blueberry',color: 'blue'},item3: {name: 'cherry',color: 'red'}}]};
var obj3 = {items: [{item1: {name: 'apple',color: 'red'}},{item2: {name: 'blueberry',color: 'blue'},},{item3: {name: 'cherry',color: 'red'}}]};

let getObject = (o, key, value) => o.find(obj => obj[key] === value);

console.log(getObject(Object.values(obj), 'color', 'red'));
console.log(getObject(obj2.collection.map((o, i) => o[`item${i+1}`]), 'color', 'red'));
console.log(getObject(obj3.items.map((o, i) => o[`item${i+1}`]), 'color', 'red'));
.as-console-wrapper { min-height: 100%; }

Object, The Object class represents one of JavaScript's data types. It is used to store various keyed collections and more complex entities. Objects can� JavaScript : find an object in array based on object's property (and learn about the "find" function) Published on March 20, 2017 March 20, 2017 • 320 Likes • 49 Comments Report this post

You can call the function recursively to reach an object that hasn't any objects-members and filter it by key and value:

function getObject(obj, k, v) {
    for (var key in obj) {
        if (typeof obj[key] === 'object') {
            return getObject(obj[key], k, v);
        } else if (key === k && obj[key] === v) {
            return(obj);
        }
    }   
}

var obj = {
  item1: {
    name: 'apple',
    color: 'red'
  },
  item2: {
    name: 'blueberry',
    color: 'blue'
  },
  item3: {
    name: 'cherry',
    color: 'red'
  }
};

var obj2 = {
  collection: [
    {
      item1: {
        name: 'apple',
        color: 'red'
      },
      item2: {
        name: 'blueberry',
        color: 'blue'
      },
      item3: {
        name: 'cherry',
        color: 'red'
      }
    }
  ]
};

var obj3 = {
  items: [
    {
      item1: {
        name: 'apple',
        color: 'red'
      }
    },
    {
      item2: {
        name: 'blueberry',
        color: 'blue'
      },
    },
    {
      item3: {
        name: 'cherry',
        color: 'red'
      }
    }
  ]
};
console.log(getObject(obj, 'color', 'red'));
console.log(getObject(obj2, 'color', 'red'));
console.log(getObject(obj3, 'color', 'red'));

How to Turn an Object into Query String Parameters in JavaScript , As a JavaScript developer, you'll often need to construct URLs and query string parameters from objects. In this guide, we'll cover various ways� Create a JSON object containing the parameters needed to query the table, which in this example includes the table name, the ExpressionAttributeValues needed by the query, a KeyConditionExpression that uses those values to define which items the query returns, and the names of attribute values to return for each item.

How to build a query string from an object with vanilla JS, Then, we can loop through the data object. var buildQuery = function (data) { // If the data is already a string, return it as-is if (typeof (data) === 'string') return data; // Create a query array to hold the key/value pairs var query = []; // Loop through the data object for (var key in data) { if (data. Media queries was introduced in CSS3, and is one of the key ingredients for responsive web design. Media queries are used to determine the width and height of a viewport to make web pages look good on all devices (desktops, laptops, tablets, phones, etc). The window.matchMedia() method returns a MediaQueryList object representing the results of

Object mapping and querying, Object mapping and querying. In this section Open a fresh JavaScript file " model.js" where we put our Store instance and any database models. This tutorial� Home › Object-Oriented JavaScript › How to Turn the Query String Into a JavaScript Object It is fairly common for any front-end web developer to examine the query string. If jQuery has taught us anything, that would be the power of abstraction: create functionality once, and then use that functionality as a tool over and over, as needed.

A Query Language for JavaScript Objects, Let's say that we have a JavaScript object like so: toString.call(obj) === '[object Array]'; } function select(obj, query, result) { var parts, ptr, term;�

Comments
  • FYI, you can use Array.isArray() to check if the object is an array.
  • Possible duplicate of How to find index of an object by key and value in an javascript array
  • I actually like your answer the most and ended up using it, but unfortunately I accepted another answer before seeing your solution. Apologies.
  • No problem. Not that you have to do it; but just that you know: you can always mark another answer as accepted, which will remove the mark from your earlier choice. However, like I commented under the accepted answer: as it currently stands, it has a bug.
  • I guess better late than never. I found out you could actually unselect an accepted answer. Thanks again for this awesomely concise solution!
  • Thanks for this, @Ele. While I admire the brevity of the solution, I won't be able to use this right now because (1) the code base is standarized on ES5, and (2) other developers who use this helper function will not know to .map() when appropriate.
  • @thdoan no problem!
  • @thdoan, I just stumbled over this comment: code base is standardized on ES5. If ES5 is a requirement, then that should be clearly mentioned in the question.