Get value from Nested Object [duplicate] - javascript

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
I am trying to get the first value for an object like:
{
"_id":"123",
"list":{"56":{"name":"Great ","amount":100,"place":"Town"},"57":{"name":"Great 2","amount":200,"place":"City"}},
"pop":[2,3]
}
This is 1 object of around 100 or so. I am trying to get the amount from the first value of list property in each of the 100 objects ? i.e. so above it would be 100
How would I do that ? I am using underscore JS ?

You are defining list as object . Object properties are in order of they defined, but we cannot trust its order . I think there is Chrome bug about it https://code.google.com/p/v8/issues/detail?id=164
the following first method gives first element from list object , this function will works most cases , if object is empty it will return undefined value.
var data = {
"_id":"123",
"list":{
"56":{"name":"Great ","amount":100,"place":"Town"},
"57":{"name":"Great 2","amount":200,"place":"City"}
},
"pop":[2,3]
};
function first( data ){
for ( var i in data ){
if ( data.hasOwnProperty(i) ) break;
}
return data.hasOwnProperty(i) ? data[i] : undefined;
}
first( data.list ).amount;
If you want to keep order of list .. define them as Array . example
var data = {
"_id":"123",
"list":[
{"id" : "56" ,"name":"Great ","amount":100,"place":"Town"},
{"id" : "57" ,"name":"Great 2","amount":200,"place":"City"}
],
"pop":[2,3]
};
and access them as data.list[0]

You can try this
function getFirstAmount(obj){
for(var key in obj){
return obj[key].amount;
}
}
If you need to get all keys, you can try this
function getAmounts(obj){
var amounts = [];
var i = 0;
for(var key in obj){
amounts[i] = obj[key].amount;
i++;
}
}
return amounts;
}
//call function
var firstAmount = getFirstAmount(obj.list);

Related

Check if value exists in array javascript [duplicate]

This question already has answers here:
Object comparison in JavaScript [duplicate]
(10 answers)
How to determine equality for two JavaScript objects?
(82 answers)
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 3 years ago.
I have this data
var selectedValue = [];
selectedValue.push({0:'Data A'});
selectedValue.push({1:'Data B'});
I want to check if my new data is already exists in that array. I'm trying to use includes()
function inArrayCheck(val) {
console.log(selectedValue.includes(val));
}
Then i try another way
function inArrayCheck(val) {
if (Object.values(selectedValue).indexOf(val) > -1) {
console.log(val);
}
}
both of them returning false when i input Data A
Objects will not be equal unless they have the same reference, even when they have the same key/value pairs. You can do the comparison after converting the objects to string using JSON.stringify with limited capability, like the order of elements in the object and the case of strings matters:
var selectedValue = [];
selectedValue.push({0:'Data A'});
selectedValue.push({1:'Data B'});
function inArrayCheck(val) {
return selectedValue.some(obj => JSON.stringify(obj) === JSON.stringify(val))
}
console.log(inArrayCheck({0:'Data A'}))
You are trying to find a value from an object which is inside an array. You can try like so:
var selectedValue = []; // this is an array
selectedValue.push({0:'Data A'}); // here you push an object to the array
selectedValue.push({1:'Data B'}); // to find the value later you need to find it inside the object!
// above three lines can also be written like so and are the same
// var selectedvalue1 = [{0:'Data A'}, {1:'Data B'}];
function inArrayCheck(val) {
selectedValue.forEach(function(element){
if (Object.values(element).indexOf(val) > -1) {
console.log('found value: ' + val);
}
});
}
inArrayCheck('Data A');
if you want to use includes you need to have an array like so:
var selectedValue = [];
selectedValue.push('Data A');
selectedValue.push('Data B');
// above three lines can also be written like so and are the same
// var selectedvalue1 = ['Data A', 'Data B'];
function inArrayCheck(val) {
console.log(selectedValue.includes(val));
}
inArrayCheck('Data A')
You forgot to go trough each value. You can also use find() function, to check if array have a value which sutisfy your condition.

How to iterate an object into an array of Object [duplicate]

This question already has answers here:
Iterate over Object Literal Values
(8 answers)
Closed 2 years ago.
I have create one object and that object I need to pass in one method where I need to iterate by using each object. Since my Obj having only values so it its not getting passed. Can any one help me into this.
My Code :
var MyObj = {
country : "Aus",
Time : "EST",
Val : "Pecific"
}
Now this MyObj I need to pass in one method:
this.someMethod(id, MyObj);
In someMethod i Have one code like
Ext.Array.forEach(MyObj, function (Value) {})
At this point it is getting failed because MyObj is not an array of object. How to correct it.
It would be very helpful if you'd provide more information.
I am not sure what you want to achieve, but there are several ways to iterate through objects.
If you want to split up your object into multiple single-key objects:
> Object.keys(MyObj).map(key => ({ [key]: MyObj[key] }))
[ { country: 'Aus' }, { Time: 'EST' }, { Val: 'Pecific' } ]
On the other hand, if you have a function that takes an array but you want to pass just this one object:
Ext.Array.forEach([MyObj], Value => ())
(But in this case you are better off just calling the function.)
var MyObj = {
country : "Aus",
Time : "EST",
Val : "Pecific"
}
//Without ext
function someMethod(id, MyObj)
{
Object.keys(MyObj).forEach(function (Value) {
console.log(MyObj[Value]);
});
}
someMethod(1, MyObj);
This code (vanilla JS) will get the keys from the Object with Object.keys and allows you to iterate over it. Works for Objects and Arrays.
You can achieve that in the following way:
var MyObj = {
country : "Aus",
Time : "EST",
Val : "Pecific"
}
function someFunction(id, obj){
var objArray = $.map(obj, function(el) {
console.log(el);
return el
});
}
someFunction(1, MyObj)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The ExtJs way
ExtJs provides Ext.Object.eachValue which is what you are searching for.
From the ExtJs documentation:
Iterates through an object and invokes the given callback function for
each iteration. The iteration can be stopped by returning false in the
callback function.
The following code iterrates over each value of MyObj and calls the callback with it.
var MyObj = {
country : "Aus",
Time : "EST",
Val : "Pecific"
}
Ext.Object.eachValue(MyObj, function (Value) {console.log(Value)});

Find index of object in array by key

I have an array of objects like so
myobj= [{"item1" : info in here},{"item2" : info in here}, {"item3" : info in here}]
I'm trying to modify one, but I only know its key. I need to pinpoint the item1 object so I can change its value (the values are random and I don't know them, so I can't rely upon them).
If I could just get the index of the item it would be pretty easy: myobj[index].value = "newvalue".
Maybe using the index isn't the best way, so if it isn't, I'm open to other ideas.
I was thinking I could try something like
myobj.objectVar
Where objectVar is the key I'm being passed (item1, for example), however this does not work, possibly because it's a variable? Is it possible to use a variable like this maybe?
If it helps, I'm using underscore.js as well.
Your guess at a solution doesn't work because you're not accessing the individual objects, you're accessing an array of objects, each of which has a single property.
To use the data in the format you've got now, you need to iterate over the outer array until you find the object that contains the key you're after, and then modify its value.
myobj= [{"item1" : info in here},{"item2" : info in here}, {"item3" : info in here}]
function setByKey(key, value) {
myObj.forEach(function (obj) {
// only works if your object's values are truthy
if (obj[key]) {
obj[key] = value;
}
});
}
setByKey('item1', 'new value');
Of course, the far better solution is to stop using an array of single-property objects, and just use one object with multiple properties:
myobj= {"item1" : info in here, "item2" : info in here, "item3" : info in here};
Now, you can simply use myObject.item1 = "some new value" and it will work fine.
You can write a function like,
function getElementsHavingKey(key) {
var objectsHavingGivenKey = [];
//loop through all the objects in the array 'myobj'
myobj.forEach(function(individualObject) {
//you can use 'hasOwnProperty' method to find whether the provided key
// is present in the object or not
if(individualObject.hasOwnProperty(key)) {
// if the key is present, store the object having the key
// into the array (many objects may have same key in it)
objectsHavingGivenKey.push(individualObject);
}
});
// return the array containing the objects having the keys
return objectsHavingGivenKey;
}
If you only want to get the index of elements having the given key
You can do something like this,
function getIndexesOfElementsHavingKey(key) {
var objectsHavingGivenKey = [];
//loop through all the objects in the array 'myobj'
myobj.forEach(function(individualObject, index) {
//you can use 'hasOwnProperty' method to find whether the provided key
// is present in the object or not
if(individualObject.hasOwnProperty(key)) {
//push index of element which has the key
objectsHavingGivenKey.push(index);
}
});
// returns the array of element indexes which has the key
return objectsHavingGivenKey;
}
Try this code:
function changeObj( obj, key, newval )
{
for( var i=0, l=obj.length; i<j; i++)
{
if( key in obj[i] )
{
obj[i] = newval;
return;
}
}
}
var myObjArray= [{"item1" : "info in here"},{"item2" : "info in here"}, {"item3" : "info in here"}]
To find and add new value to the object inside an array:
myObjArray.forEach(function(obj) {
for(var key in obj) {
// in case you're matching key & value
if(key === "item1") {
obj[key] = "update value";
// you can even set new property as well
obj.newkey = "New value";
}
}
});
You can access objects the same using their index, even the object inside the original object.
Is this kind of what your looking for:
var otherObj = [{"oitem":"oValue"}];
var myobj= [{"item1" : otherObj},{"item2" : "2"}, {"item3" : "tesT"}];
myobj[0].item1[0].oitem = "newvalue";
alert(myobj[0].item1[0].oitem);

Sending array through post jquery [duplicate]

This question already has answers here:
Convert javascript object or array to json for ajax data
(2 answers)
Closed 8 years ago.
I now this question has been asked before but I am trying to work this out since this morning and I can't get it right.
I have a global variable named items
I have a .ajax request that I need to send the contents of the items array
Items is like this
items = new Array();
for (var i = 0; i < 10; i++)
{
//just populating the list
var item = [];
item['some_stuff'] = 'string';
item['some_int'] = 373;
items.push(item);
}
//here is the request
if (items.length > 0)
{
$.ajax({
type : "POST",
url : "/grad1/adaugaComanda.php",
data : { "stuff" : items},
success : function (data){
alert(data);
// window.location = '/dashboard.php?categ=5&sel=1';
}
});
}
//
The request is executed but data is not sent. I tried to use JSON.stringify on the array but it returns empty ([[]]).
Any ideas what I am doing wrong ?
//just populating the list
var item;
This declares a variable called item but does not give it a value to it so it is undefined
item['some_stuff'] = 'string';
This attempts to assign a value to the some_stuff property of undefined. This isn't allowed, so JS will throw an exception and script execution will cease.
You aren't making a request at all, because your script isn't getting far enough to do that.
You need to assign an object to item:
var item = {}
You have edited your question so your code now reads:
var item = [];
You still need to use a plain object here ({} not []). Array objects should only have numeric indexes. jQuery will ignore named properties on an array when serializing it.

How to check whether a given string is already present in an array or list in JavaScript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Javascript - array.contains(obj)
Best way to find an item in a JavaScript Array ?
I want to check, for example, for the word "the" in a list or map. Is there is any kind of built in function for this?
In javascript you have Arrays (lists) and Objects (maps).
The literal versions of them look like this:
var mylist = [1,2,3]; // array
var mymap = { car: 'porche', hp: 300, seats: 2 }; // object
if you which to figure out if a value exists in an array, just loop over it:
for(var i=0,len=mylist.length;i<len;i++) {
if(mylist[i] == 2) {
//2 exists
break;
}
}
if you which to figure out if a map has a certain key or if it has a key with a certain value, all you have to do is access it like so:
if(mymap.seats !== undefined) {
//the key 'seats' exists in the object
}
if(mymap.seats == 2) {
//the key 'seats' exists in the object and has the value 2
}
Array.indexOf(element) returns -1 if element is not found, otherwise returns its index

Categories

Resources