Get/find javascript object by its parameter - javascript

Considering I have an array of objects, and all objects represent something out of a database, thus they have an unique identifier.
Now I also have the ID and the correct array. How do I search each object in that array where the parameter 'id' equals my ID. (The point is, I don't know the internal identifier for that object. All I have is an ID and I need the entire object for description, last_user, created etc..)
Object
created: "2011-06-08 15:47:11"
description: "Something new.."
id: "1"
last_user: "1"
P.s. I have jQuery embedded, so if there's no default way, a jQuery function would suffice.

$.grep() should do it. In the following example arr is your array of objects. It will find the element that has an id of 1.
var obj = jQuery.grep(arr, function(el, i){
return el.id == 1;
})[0];

You could loop through your array of objects, and check for each one if yourObject.id is equal to the id you are looking for. Then you'll be able to get the other fields, such as yourObject.created

Related

How to match node key with the array of objects key in Javascript?

I have array of objects. I want to match a groupName key with the object I got.
The code that I'm using is:
importedgroups.some(obj => obj.groupName === node.groupName)
Here importedgroups is array of objects. It has objects with key name groupName. I have returned a object from some function. And when I try to check whether the returned object groupName is matching with the importedgroups then it is returning false.
[{"groupName":"omnidocs_group","groupImportedAs":"Normal"},{"groupName":"omnidocs_group","groupImportedAs":"Normal","groupDistinguishName":"tmpDn"},{"groupName":"group_ouéñ","groupImportedAs":"Normal","groupDistinguishName":"tmpDn"}]
But the object which I have has groupName exactly matching with the one object of importedgroups array.
How can I solve this?. Is there any alternative to that?

Get nth element of a key in an object

I'd like to return the third node (hello3.com) of the key hello.com in javascript object.
nodes = {
"hello.com":
{
id:"hello1.com",
id2:"hello2.com",
id3:"hello3.com"
}
}
I know that I can fetch all the key/values like this:
newobject = nodes["hello.com"];
but how would I get the third. I'm aware that you can't count on the order in an object. If not, can I pull just the third by maybeb id3.
You answered your own question when you said that you can't count on the properties of an object to be in any certain order. If your properties are sequential in nature (your properties were counting up in your example), then I would suggest trying to use an Array.
nodes = {
"hello.com": [
"hello1.com",
"hello2.com",
"hello3.com"
]
};
In the above example, you would access the 3rd property with
nodes["hello.com"][2]
The double bracket notation is because "hello.com" is in quotes to allow a . in the name. If the key didn't require quotes, like helloCom as an example, you could use
nodes.helloCom[2]
Beyond this, if you name your keys sequentially, then you can impose an "order". It's not that any property is literally before or after another, but rather that you have informed yourself of what order YOU intend them to be.
You can try this,
nodes = {
"hello.com": {
id: "hello1.com",
id2: "hello2.com",
id3: "hello3.com"
}
}
console.log(nodes["hello.com"]["id3"]);
Use:
nodes['hello.com'].id3 or nodes['hello.com']['id3']
Both are corrent way to get id3 data from given object
BY INDEX :
About accessing by index, you can not achieve it directly. the closest you can get is array of keys but that also do not guarantee the order of keys returned. See this answer provided on other thread.
for (var i in nodes["hello.com"]) { console.log(i);//logs id,id2,id3 };
BY NODENAME:
nodes["hello.com"] returns object. You can use key to access the value by
1) using dot notation:
nodes["hello.com"].id3
2) or by bracket notation
nodes["hello.com"]["id3"]
Try one of the following expressions
nodes["hello.com"]["id3"]
or
nodes["hello.com"].id3

Javascript array insertion

I have an array in javascript which looks like this:
var arr = [
{ // first
id : '45'
name : 'dsada'
},
{
id : '45'
name : 'dsada'
},
/* ... */
];
I want to add more data to the first index of it, e.g. country:'Egypt'.
Which function should I use?
Or how to push values to specific index in array?
I have used push and splice methods but I can't figure it out.
arr[0].country = 'Egypt'
Set the country property.
Scimonster's answer is correct, but it is better if you take a look to the documentation. Your question highlight some confusion on basics.
Documentation
The Array.prototype.push() method adds one or more elements to the end of an array and returns the new length of the array.
The Array.prototype.splice() method changes the content of an array, adding new elements while removing old elements.
The Object.prototype represents the Object prototype object.

Get object property value

I have an object that contains an array of objects from which I need to get a value of their properties.
As an example this is what I need to get:
Stronghold.bins.models[0].attributes.entity.title
Which returns "Stronghold Title 1"
function grabItemName(){
var itemName=$(Stronghold.bins).each(function(){
return this.models[0].attributes.entity.title == title;
console.log(itemName);
})
};
(if there is a better way for me to ask this question please let me know)
I apologize if this was poorly asked!
The current issue is that it does not understand the array value '[0]' and cannot read it as it is undefined. What do I need to do to grab the 'title' value of all items in the array?
What do I need to do to grab the 'title' value of all items in the array?
That's what .map [docs] is for. It lets you map each value in an array to another value.
In the following I assume you want to iterate over each Stronghold.bins.models, because iterating over Stronghold.bins does not make sense with the provided information:
var titles = $.map(Stronghold.bins.models, function(obj) {
return obj.attributes.entity.title;
});
// `titles` is now an array containing `.attributes.entity.title;` of
// each object.
The current issue is that it does not understand the array value '[0]' and cannot read it as it is undefined.
Well, that won't happend anymore ;) In your example you where iterating over the properties of the Stronghold.bins object. One of these properties is models itself (!) and I doubt that any other property value has a models property.
Try using the other version of the each function:
$.each(Stronghold.bins, function () {
});
The version you are using is for looping through an element on the page, e.g $('body div p').each(function() {}), which isn't what you want in this instance: You want to loop over the values contained in Stronghold.bins.

How do I access the first key of an ‘associative’ array in JavaScript?

I have a js 'associative' array, with
array['serial_number'] = 'value'
serial_number and value are strings.
e.g. array['20910930923'] = '20101102'
I sorted it by value, works fine.
Let's say I get back the object 'sorted';
Now I want to access the first KEY of the 'sorted' array.
How do I do it? I can't think I need an iteration with
for (var i in sorted)
and just stop after ther first one...
thanks
edit: just to clarify, I know that js does not support associative arrays (that's why I put it in high commas in the Title).
2021 Update
Since ES6, properties with string keys are enumerated in insertion order. Here's a nice summary. My original answer from 2010 was correct at the time and is preserved below:
Original answer
JavaScript object properties are specified to have no order, much though many people wish it were different. If you need ordering, abandon any attempt to use an object and use an Array instead, either to store name-value objects:
var nameValues = [
{name: '20910930923', value: '20101102'},
{name: 'foo', value: 'bar'}
];
... or as an ordered list of property names to use with your existing object:
var obj = {
'20910930923': '20101102',
'foo': 'bar'
};
var orderedPropertyNames = ['20910930923', 'foo'];
Try this:
// Some assoc list
var offers = {'x':{..some object...}, 'jjj':{...some other object ...}};
// First element (see attribution below)
return offers[Object.keys(offers)[0]];
// Last element (thanks to discussion on finding last element in associative array :)
return offers[Object.keys(offers)[Object.keys(offers).length - 1]];
Actually JavaScript doesn't support associative arrays, so you can't loop through it in an implied order (e.g. you can't access it via the indexer property array[0] won't access the first element in your object). The syntax is what makes it look like it does, but in reality it doesn't. So you have no "Order" to your objects.
http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
Javascript does not have, and does not
support Associative Arrays. However…
All arrays in Javascript are objects
and Javascript's object syntax gives a
basic emulation of an associative
Array. For this reason the example
code above will actually work. Be
warned that this is not a real array
and it has real pitfals if you try to
use it. The 'person' element in the
example becomes part of the Array
object's properties and methods, just
like .length, .sort(), .splice(), and
all the other built-in properties and
methods.
Just thinking off the top of my head, but could you have another array with the key value pairs swapped?
So the answer would be arrayKeyValueReversed['20101102'] = '20910930923';
When you sort the array, use the first item (array[0]) as the key to get the value in the arrayKeyValueReversed.

Categories