Alter array object using loop - javascript

var arr = [{id:1,"name":"John"},{id:2,"name":"James"}]
$.each(arr, function(){
if(this.id == 1){
//change john to Johnathan
}
});
without using key, is it possible to alter array object?

Sure you can do that by converting the object to a string if you are looking for a hack. What is it that you are looking to do?
var arr = [{id:1,"name":"John"},{id:2,"name":"James"}]
$.each(arr, function(i){
if(this.id == 1){
arr[i] = JSON.parse(JSON.stringify(this).replace("John", "Johnathan"))
}
});

You do like this in the loop:
var arr = [{id:1,"name":"John"},{id:2,"name":"James"}]
$.each(arr, function(){
if(this.id == 1){
this.name = 'Johnathan';
//change john to Johnathan
}
});

The only way I can think of would change all "John" values to "Johnson" in all properties without explicitly using a property name. You can loop all properties on an object.
for (var i = 0; i < arr.length; i++) {
for (var prop in object) {
if (object.hasOwnProperty(prop)) {
if (arr[i][prop] === 'John') {
arr[i][prop] = 'Johnson';
}
}
}
}
This probably won't work for you, but it's the only way to grab a value on an object without using the property name explicitly.

then i think you need to replace whole array's object with having id == 1
here is what i tried
for(var i = 1;i<arr.length;i++){
if(this.arr[i].id == 1){
this.arr[1] = {'id':'1','name':'Johnathan'};
}

Related

NodeJS: How to check if a key exists in an array of JSON object

I have an array of JSON objects imdb and I want to check if a key exists. I have tried couple different methods but none of them shows the correct result. I looked into this post but doesn't help. Below code
var imdb = [{"123":"hi"}, {"234":"hello"}]; //array of JSON object
var valEventTime = 123; //key I want to find if exists
//approach 1
function getValueByKey(key, data) {
var i, len = data.length;
for (i = 0; i < len; i++) {
if (data[i] && data[i].hasOwnProperty(key)) {
return data[i][key];
}
}
return -1;
}
if(getValueByKey(valEventTime, imdb) > -1){
console.log("Yes");
}
else {
console.log("NOT")
}
//approach 2
if (imdb[valEventTime]) {
console.log("Yes");
} else {
console.log("NOT")
}
//approach 3
var keys=Object.keys(imdb)
for(var i=0;i<keys.length;i++){
if(keys[i]==valEventTime)
{//check your key here
console.log("Yes")
}
else console.log("NOT")
}
The output always shows NOT even though I am searching for a key that already exists (123). Please suggest.
The problem with your solution is that you are trying to search for a integer key where as your json key is a string.
var imdb = [{"123":"hi"}, {"234":"hello"}]; // key is string
var valEventTime = 123; // key is integer
var imdb = [{"123":"hi"}, {"234":"hello"}];
var valEventTime = "123";
var obj = imdb.some((val) => {
return Object.keys(val).includes(valEventTime);
})
console.log(obj);
You can use Array.some() to determine if an array contains a value. For each item you want to use the Array.includes() function to check for your variable for the items return from Object.keys() on each entry. In your example your variable is an integer and the key is a string - you may want to be more specific in your matching.
var imdb = [{"123":"hi"}, {"234":"hello"}];
var valEventTime = "123"; // use a string to match the keys
// use Array.some() to loop through each item and short circuit when we return true
var hasKey = imdb.some(function(movie) {
// get the object keys as an array and see if that array contains your variable
// returning true will also return true from Array.some()
return Object.keys(movie).includes(valEventTime);
});

Remove false values in object

The problem that I'm facing is -removing the values in the onject that has the property false
Here is the object
var myObj={105:true,183:false,108:true,106:false}
I'm able to get the values in an array by using the following logic:
Object.keys(myObj) gives ["105","183","108","106"]
But I need a way to remove the values that have the property false and generate as ["105",108"].Can you help me out ?
You have the keys of the object in an array. Run filter over it.
var myObj={105:true,183:false,108:true,106:false};
var result = Object.keys(myObj).filter(function(x) {
return myObj[x] !== false;
});
// result = ["105", "108"]
I've just created a solution to your problem on JSBin: Working Demo
Please find below the code:
var myObj={105:true,183:false,108:true,106:false};
var myArray = [];
function RemoveFalseAndTransformToArray () {
for (var key in myObj) {
if(myObj[key] === false) {
delete myObj[key];
} else {
myArray.push(key);
}
}
}
RemoveFalseAndTransformToArray();
console.log("myObj: ", myObj);
console.log("myArray: ", myArray);
// result = ["105", "108"]
Please, let me know if you have any question.
To remove those properties you can use this algorithm:
for (k in myObj)
{
if (myObj.hasOwnProperty(k) && myObj[k] === false)
{
delete myObj[k];
}
}
If you are just interested in the keys of non-false values, you can use:
var keys = Object.keys(myObj).filter(function (k) {
return myObj[k] !== false;
});
The hasOwnProperty() check is necessary because objects may contain non-user properties (such as prototype) which you really don't want to mess with.
You need to iterate over the object using for...in loop
var myObj={105:true,183:false,108:true,106:false}
for(var key in myObj){
if(myObj.hasOwnProperty(key) && myObj[key] == false){
delete myObj[key];
}
}
console.log(JSON.stringify(myObj)) //{"105":true,"108":true}
console.log(Object.keys(myObj)) //["105", "108"]
ES6 has a one line way to do this, this mutates the original array!
Object.keys(myObj).map(key => !myObj[key] && delete myObj[key])
to avoid this use the spread operator
const filteredObj = [...myObj]
Object.keys(filteredObj).map(key => !filteredObj[key] && delete filteredObj[key])

Replace multiple string items in the array

I have an array that shows this value "135_1,undefined,undefined"
I have to find the "undefined" in the above array and then replace it with "0_0".Undefined can occur multiple times in the array.
I used
var extra = myVariable.replace("undefined", "0_0");
alert(extra);
but then I have to use this three times so that every single time it can search one and replace it.
I have also used this::
for (var i = 0; i < myVariable.length; i++) {
alert(myVariable[i]);
myVariable[i] = myVariable[i].replace(/undefined/g, '0_0');
}
alert(myVariable);
but it did'nt solved my purpose.
String.prototype.replace is a method accessible to strings. undefined is not a string.
This might help you.
for (var i=0, len=arr.length; i<len; i++) {
if (arr[i] === undefined) {
arr[i] = "0_0";
}
}
alert(JSON.stringify(arr));
You could also use Array.prototype.map for this. Note, it only works in IE >= 9
arr = arr.map(function(elem) {
return elem === undefined ? "0_0" : elem;
});
Since the question is tagged with jquery you can use $.map():
var extra = $.map(myVariable, function(item) {
return item || '0_0';
}
This will return a new array whereby each item comprising (in your case) an empty string or undefined is replaced by '0_0'.
var arr = ['135_1',undefined,undefined];
while(arr.indexOf(undefined) != -1) {
pos=arr.indexOf(undefined);
arr[pos]='0_0';
}

Change a particular object in an array

Starting with an array of objects:
var array=[
{name:"name1",value:"value1"},
{name:"nameToChange",value:"oldValue"},
{name:"name3",value:"value3"}
];
How do change the value of a given property of one of the objects when another given property in the object is set to a given value?
For instance, starting with my array shown above, I wish to change value to "newValue" when name is equal to "nameToChange".
var array=[
{name:"name1",value:"value1"},
{name:"nameToChange",value:"newValue"},
{name:"name3",value:"value3"}
];
PS. To create the initial array, I am using jQuery's serializeArray(), and I do not wish to change the value of <input name="nameToChange">. I suppose I can change its value, use serialArray(), and then change it back, but this sounds more complicated than necessary.
The easiest way is to iterate over this array:
var i = arr.length;
while (i--) {
if (arr[i].name === 'nameToChange') {
arr[i].value = 'newValue';
break;
}
}
You won't be able to do the same stuff with native 'indexOf', as objects are to be compared.
for (var i = 0; i < array.length; i++) {
if (array[i].name == 'nameToChange') {
array[i].value = 'value';
break;
}
}
fiddle Demo
You need to go through all the elements and search for the required one and then replace with the value.
for(var i = 0; i < array.length; i++){
if(array[i]["name"] == str) {
array[i]["value"] = newValue;
break;
}
}
It's 2013; skip all the messy for loops and use forEach. It's much simpler and semantically cleaner:
array.forEach(function (e) {
if (e.name == 'nameToChange')
e.value = 'newValue';
})
Since you are using jQuery, you could use this:
$.each(array, function () {
if(this.name == 'nameToChange') this.value = 'value';
});
Fiddle

Lowercase of object value in array with underscore js

Let's say I have this JSON data in a data variable
[{"id":"1","module_id":"1","title":"Test",
"start_date":"2012-11-12" "end_date":"2012-11-18"},
{"id":"8","module_id":"1","title":"This is OK",
"start_date":"2013-01-14","end_date":"2013-01-31"}]
How do I use underscore.js to get following result?
[{"id":"1","module_id":"1","title":"test",
"start_date":"2012-11-12","end_date":"2012-11-18"},
{"id":"8","module_id":"1","title":"this is ok",
"start_date":"2013-01-14","end_date":"2013-01-31"}]
Can I do this with invoke ?
You can do this easily with Lo Dash's _.mapValues function:
_.mapValues(objs, function(s){
return _.isString(s) ? s.toLowerCase() : s;
});
If you're already dealing with an object (or parsed JSON), you can loop and create a new one:
var objs = [{"id":"1","module_id":"1","title":"Test", "start_date":"2012-11-12", "end_date":"2012-11-18"},{"id":"8","module_id":"1","title":"This is OK", "start_date":"2013-01-14","end_date":"2013-01-31"}];
var out = [];
for(var i=0; i<objs.length; i++) {
var outObj = {}
for(var prop in objs[i]) {
var val = objs[i][prop];
if(prop === 'title') {
val = val.toLowerCase();
}
outObj[prop] = val;
}
out.push(outObj);
}
console.log(out);
http://jsfiddle.net/uY36J/
If you have array of objects:
for(var i = 0; i < array.length; i++) {
for (var prop in array[i])
// condition here
array[i][prop] = array[i][prop].toLowerCase();
}
console.log(array)
Same with underscore (I don't think it's much shorter - you still need two loops here. More readable - maybe, but not shorter)
_.each(array, function(obj) {
_.each(obj, function(value, key) {
// condition here
obj[key] = value.toLowerCase();
});
});
You can separate the object in two arrays, one with the keys and the other with the values, then use _.map to lowercase the strings.
var objs = [{"id":"1","module_id":"1","title":"Test", "start_date":"2012-11-12", "end_date":"2012-11-18"},{"id":"8","module_id":"1","title":"This is OK", "start_date":"2013-01-14","end_date":"2013-01-31"}];
_.map(objs,function(element) {
return _.object(_.keys(element), _.values(element).map(function(value) {
return _.isString(value)? value.toLowerCase():value;
}));
});
you see, I'm checking if it's a string we're dealing with, to avoid calling toLowerCase on other types.
Lowercasing both keys and values is trivial as well
_.map(objs,function(element) {
return _.object(
_.keys(element).map(function(key) {
return _.isString(key)? key.toLowerCase():key;
}),
_.values(element).map(function(value) {
return _.isString(value)? value.toLowerCase():value;
})
);
});
Caveat: this will not operate on nested objects. ¯\_(ツ)_/¯

Categories

Resources