How to update an array of objects? - javascript

For example,
{
id:"monday",
names:[
{one:"white", two:"pink"},
{uno:"blanco", dos:"rosado"}
]
}
How would you change white to black?
So far, I've got this:
r.db.table.get('monday').update({
names: r.row("names").nth(0)
})
Which specifies the 0th index of names, but not sure how to further specify the one field and then change it.

What you have so far is pretty correct but you replace names with its first sub-object (I guess you saw that result already).
You just need to use a merge to alter the sub-object, and a changeAt on names to put the altered sub-object in the array, just like this:
r.db.table.get('monday').update({
names: r.row('names').changeAt(0, r.row('names').nth(0).merge({one: 'black'}))
})
Hope this helps!

Maybe your data is stored in an object with the name of obj; something like
var obj = {...}
you can make this work:
obj.names[0].one = "black";
I have actually tried it using firebug no issues.
Each element in the array is independent so no worries.

First off all, you should use replace instead of update.
Get record without names field.
merge it with new names (remove 1st element from it, add at the 1st position new element in which we replaced white to black in one field)
Something like this:
r.db.table.get('monday').replace(function(doc){
return doc.without({names: true}). merge({
names: doc("names").deleteAt(0).prepend(doc("names").nth(0).merge({
one : "black"
}))
})
})

Related

AngularJS - Get object index in custom filter

I have made a custom filter in controller but can't get index or size of iterated json. Calling program.length gets me undefined. Any ideas?
$scope.filterFn = function(program){
if(case){
return true;
}
console.log(program.length);//undefined
return false;
};
try to use this code to get object length.
Object.keys(program).length;
try : How to display length of filtered ng-repeat data, so you can access size by $scope.filtered.length like the example.
Are there any more filters before this? Coz previous filters decide input for next filter?
The length() method is only available on an array [].
In this case you are trying to get the size of a json object {}, please note this does not have a length. If you need to see how many items exist in this object, you can try to first convert all the keys into an array by using Object.keys(program) which will give you an array.
If program originally looked like this:
{
foo: 'some value',
bar: 'another value'
}
using Object.keys(program) will give you ['foo', 'bar'] On this array you can now call the length method, so that you have Object.keys(program).length, which in this case would give you 2.

How can I add elements to a part of a json by using jquery

I try to add elements in a particular way to the following JSON:
var data = [{"name":"google",
"ip":"10.10.10.01",
"markets":[{"name":"spain","county":"6002,6017,6018,6019,6020"},
{"name":"france","county":"6003,6005,6006,6007,6008,6025,6026,6027,6028,6029"},
{"name":"japan","county":"6004,6021,6022,6023,6024"},
{"name":"korea","county":"6000,6013,6014,6015,6016"},
{"name":"vietnam","county":"6001,6009,6010,6011,6012"}]},
{"name":"amazon",
"ip":"10.10.10.02",
"markets":[{"name":"usa","county":"10000,10001,10002,10003,10004,10005"}]},
{"name":"yahoo",
"ip":"10.10.10.03",
"markets":[{"name":"japan","county":"10000"}]}];
I want to add this element to the json:
newData = [{"name":"amazon",
"ip":"10.10.10.02",
"markets":[{"name":"mexico","county":"9000"}]}];
The result might be exactly this:
var data = [{"name":"google",
"ip":"10.10.10.01",
"markets":[{"name":"spain","county":"6002,6017,6018,6019,6020"},
{"name":"france","county":"6003,6005,6006,6007,6008,6025,6026,6027,6028,6029"},
{"name":"japan","county":"6004,6021,6022,6023,6024"},
{"name":"korea","county":"6000,6013,6014,6015,6016"},
{"name":"vietnam","county":"6001,6009,6010,6011,6012"}]},
{"name":"amazon",
"ip":"10.10.10.02",
"markets":[{"name":"usa","county":"10000,10001,10002,10003,10004,10005"},
{"name":"mexico","county":"9000"}]},
{"name":"yahoo",
"ip":"10.10.10.03",
"markets":[{"name":"japan","county":"10000"}]}];
I tried to use :
$.extend(data.markets, newData)
$.extend(true, data, newData); //this works only in the case every element is new.
but nothing works the way I pretend.
Could anyone give me a solution?
Thanks in advance.
You haven't created JSON, you've created a JavaScript literal object.
You could add this particular piece of newdata by
data[1].markets.push({"name":"mexico","county":"9000"})
Because you are dealing with javascript objects, you can write a function to check for the existence of data[n] and push data.
You have an array of objects, where each object is like the following:
var item = {"name":"...",
"ip":"...",
"markets":[ /*some objects here*/];
}
So why not just creating your custom method to insert elements? It could search in the array if an item with the same name and ip exists, and then:
If it does exist: append the markets to the existing item markets attribute (maybe you need to check again if they already exist). UPDATE:The code that #jasonscript added in his answer will do the job: once you have found where to add the market, just add it to the array. Again, maybe you'll have to check if that market was already in the array. Using jQuery it will be: $.extend(true, data[i],newData)
If it doesn't exist: just add the item to the array: $.extend(true, data,newData)
Stealing a little code from another answer:
$.each(data, function(item){
if(item.name == newData[0].name && item.ip == newData[0].ip) {
item.markets.push.apply(item.markets, newData[0].markets);
}
}
This assumes that you know that all the market items in the new object are different to the existing ones - otherwise you'd have to do a nested foreach or something. If you can change the notation of the objects a little you could think about using a dictionary-like object for Markets to make that a little cleaner.
In fact, changing data from an associative array would probably work for that too. Then you could easily check for existence with:
if(data[myNewDataName]){
//add to markets
} else {
data[myNewDataName] = myNewData;
}

When array length = 0, it stills shows as 1

I am dealing with an array that I want to delete an object from and return the new length of the array. For all other numbers, it works - but for one item, it does not. Not sure how to fix it so that the array length is 0 after the only object is deleted. My code is below:
Here's an example where I had one object in the 'player' array:
function deletecamera(id){
alert('before the splice, player length =' + player.length); //returns 1
delete player.splice((id),1);
i=0;
for (i=0;i<player.length;i++){
player.id=i;
}
alert('after reassigning, player length =' + player.length); // still returns 1?!
refreshlist();
}
the delete keyword doesn't remove the object from the array, it sets its value to undefined, so the size of the array stay the same.
See example here: http://jsfiddle.net/up5XX/
If you want to remove the first element from the array player using .splice, you can do this:
player.splice(0, 1);
yeah, thinking a bit more about this, I bet it will work if you change this line:
delete player.splice((id),1);
to
player.splice((id),1);
some weird codes there.
An array in JS is an object that can hold multiple [elements]. But just like with any other JS object you can add more members to it by just saying myArrayName.someMemberName = something. This will not be 'in' the array as if it was an element. This is even the JS poor mans way for an 'associative array’. This is what you are doing now with the .id = ...
You need to change
player.id = i;
into something like
player[i].id = i;
(or something like it. Don't know what the goal is there. I guess you want to reorder all Id's after deleting one in between.)
futhermore ... change the splice line to just this:
player.splice(id,1);
and remove the extra line with just:
i=0;
But I now realise these all are tips but no solution to your problem.
Can you please add
alert('trying to remove id ' + id);
and confirm that you do at least once try to delete id 0 ?

How to find data from array in mongodb

I have collection like this:
{
"name":"silver",
mywants:[
{"_id":objid(545454ddfdf5),mark:{"english":100,"math":100,"science":100}},
{"_id":objid(5878784dfd5d),mark:{"english":100,"math":100,"science":100}},
{"_id":objid(5454dfd44545),mark:{"english":100,"math":100,"science":100}},
{"_id":objid(541dfee88245),mark:{"english":100,"math":100,"science":100}},
]
}
I want to find that given objid is exist in mywants array or not. Then if exist that objid i want that exist object id document to my callback function so i have tried like this
collection.find("{"name":"silver"},{"mywants._id":objid}).toArray(function(err,res)
{
console.log(JSON.stringify(res));
})
But, I got output like
[{"Mywant":[{"_id":"5128b9bc046802720b000003"},
{"_id":"5128c190046802720b000004"},
{"_id":"5128c359175e1aa80b000001"}],"_id":"5128b71455e4e0540b000002"}
]
But i want like this
{"_id":objid(545454ddfdf5),mark:{"english":100,"math":100,"science":100}}`,
How to find?
You have to call
collection.find({"name":"silver", "mywants._id":objid}).toArray(…)
instead of
collection.find({"name":"silver"},{"mywants._id":objid}).toArray(…)
. The former one represents a query with two expressions ("name":"silver" AND "mywants._id":objid) while the latter one is one expression ("name":"silver") and one projection ("mywants._id":objid) [controls the fields to return]. More info at http://docs.mongodb.org/manual/reference/method/db.collection.find/.
You have typo in your code, it is not ver clear what youwant. Based on your sample with typo and output you want (again with typo) I assume this is what you meant:
-You are doing a find on name:"silver" and want back mywants._id field (has typo) with that syntax.
Instead I assume you meant to find:
name:"silver" AND "mywants._id" : someSpecificId
and output corresponding mywants entry:
db.collection.find({"name":"silver","mywants._id":objid}, {"mywants.$":1, _id:0}).pretty()

How to instantiate an array when a user inputs?

When a user inputs text I want to create an array with the name of the inputted text and add it to array logNum. I've tried like this but it doesn't work:
logNum.push(var document.getElementById("buttonInput").value.toString()[]);
Any ideas?
Assuming you've yet created your logNum array, you can do this :
logNum.push([document.getElementById("buttonInput").value]);
The [something] notation creates a new array whose first element is something.
i'm not sure i understood you, but try this:
logNum.push( window[ document.getElementById("buttonInput").value ] = [] );
first, we generate out array: window[ document.getElementById("buttonInput").value ] = [] this creates an array with a user-input name.
and remember that assignments always returns the value of right-hand-side. so new array will be returned.
then, push the returned value to logNum array.

Categories

Resources