Remove a record in a Object Array jQuery - javascript

EDIT : Included more details
Hi I have a Object Array in jQuery which looks like this,
My question is how can I delete a record from that object array by columnheader as parameter. I know there is this
var result = $.grep(records, function(e){ return e.columnheader == currentheader; });
but grep i only used to check if there's a matching data based on currentheader that i passed in. What if I want to delete?
I want to delete a record on the fly as I am looping in that object array, lets I have. data contains all object arrays that is shown in the image.
$.each(data, function(key,value) {
// Let's say I want the code here to delete a record in the current object array that I'm looping into.
});
Thanks

You can use filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
arr = arr.filter(function(e) {
return e.columnheader !== currentheader;
});
Demo
var arr = [{
name: 'John Skeet',
rank: 1
}, {
name: 'T.J.Crowder',
rank: 10
}];
console.log(arr);
arr = arr.filter(function(e) {
return e.rank !== 10
});
console.log(arr);
UPDATE
I want the code here to delete a record in the current object array that I'm looping into
Changing a property from object in array.
var arr = [{
name: 'John Skeet',
rank: 1
}, {
name: 'T.J.Crowder',
rank: 10
}];
$.each(arr, function(index, obj) {
if (obj.rank === 10) {
arr[index].rank = 9;
}
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

You can use the JavaScript splice method to do it. First find the index of your object in the array then use the method like that :
your_array.splice(obj_index,0);
EDIT
The easy way but not optimized is to use a for loop to get the index, a better solution is to use linq.js to get the object, then your_array.indexOf(your_obj);
EDIT 2
You can download linq.js here Linq.js
You can use it like this:
function DelteObjFromArray(your_value){
var objToDelete = Enumerable.From(your_array).Where(function (x) { return x.your_property == your_value; }).FirstOrDefault();
var objIndex = your_array.indexOf(objToDelete);
your_array.splice(objIndex,1);
}

Related

How to find the name property from an array of Objects

I am trying to get the value from an array of objects given the id, but I am not able to make it working. The problem is that I have an array of objects, so I don't know how to iterate over them. I know using the .map method could be a possible solution, but I'm new on this.
my method is that given a Id, it has to return me the name from the same object.
How could I iterate over them? I am using this actually:
getName(field_id: any): any {
var aux = 0;
var obj = this.customFields[aux].filter(function (obj) {
return obj.name === field_id;
})[0];
aux ++;
}
where aux is an iterator. Ofc is not working.
considering array containing the objects, you can just use the filter function, no neeed to use the indexer
var arr = [
{id: 1, name: "something"},
{id: 2, name: "something1"},
{id: 3, name: "something2"},
{id: 4, name: "something3"},
{id: 5, name: "something4"}
]
var id=3
var obj = arr.filter(function(obj) {
return obj.id === id;
})
console.log(obj[0].name)
I think your issue is that you compare the name with the id. If you want to avoid loops:
// This find the correct entry corresponding to the id you are looking for
var correctField = this.customFields.find(function(field) {
return field.id === field_id;
});
// Then you get the name from the entry
var nameToFind = correctField && correctField.name;
You might have to replace find depending on your browser support.
A way to replace it:
this.customFields.filter()[0]
You can simply use for loop as below
var arr = [{id:1,name:"abc"},{id:2,name:"pqr"},{id:3,name:"lmn"}]
function getName(id){
for(var i=0;i<arr.length;i++)
if(arr[i].id==id)
return arr[i].name;
return null
}
getName(2);// pqr

Check if an object has a key in javascript

I have two arrays of objects, and I want to filter the first one according to whats on the second one. Here's an example:
var ary1 = [{id: 23, title: 'blabla'},{id:43, title: 'bleble'}, {id:54, title:'blibli'}];
var ary2 = [{id:23},{id:54}, {id:65}];
So in this case what I want to return is an array with the objects that have id's 23 and 54 of the first array, with all its possible properties (in this case, title).
Could you give me any hint that could help me?
Get a list of the indexes you want to search on using map:
var indexes = ary2.map(function (el) {
return el.id;
});
filter the results based on the list of indexes:
var result = ary1.filter(function (el) {
return indexes.indexOf(el.id) > -1;
});
DEMO
This might help you.
Loop through ary2, building up an array of each id value (let's call this array existingIds).
After that loop, now loop through ary1. For each item in ary1, check to see if the id value exists in the existingIds array that we just built up. If it does, append the current item to a result array.
I could write the code for you, but it will be a better learning experience if you first try this yourself :)
Might as well make use of some functional programming built into javascript.
filteredResults = ary1.filter(function(ele){
return (ary2.map(function(idobj){return idobj.id;}).indexOf(ele.id)>-1)
})
filter(function) will iterate through each element of an array, passing it through a callback function. From within that callback iff a true is returned, that value is kept. If false, that value is filtered out.
Also map(function) will iterate through each element of an array passing a callback value as well. All values returned from map callback will be injected into the result. So we can take the id from each element in ary2 and return it in the map function.
var ary1 = [{id: 23, title: 'blabla'},{id:43, title: 'bleble'}, {id:54, title:'blibli'}];
var ary2 = [{id:23},{id:54}, {id:65}];
//Filter for the available ID's, store the resulting objects in a new array
filteredResults = ary1.filter(function(ele){
//map creates an array of just ID's
return (ary2.map(function(idobj){return idobj.id;}).indexOf(ele.id)>-1)
})
//now do whatever you were planning on doing with your results/
var res = document.getElementById("results");
filteredResults.forEach(function(ele){
res.innerHTML+="<li>{id:"+ele.id + ",title:" +ele.title+"}</li>"
})
console.log(filteredResults);
<ul id="results"></ul>
try this:
var ary1 = [{id: 23, title: 'blabla'},{id:43, title: 'bleble'}, {id:54, title:'blibli'}];
var ary2 = [{id:23},{id:54}, {id:65}];
var newary=[];
for(x in ary1){
for(y in ary2){
if(ary1[x].id == ary2[y].id){
newary.push(ary1[x]);
}
}
}
console.log(newary);// here newary will be your return newary;

Sort javascript key/value pairs inside object

I have some problem with sorting items inside object. So I have something like this:
var someObject = {
'type1': 'abc',
'type2': 'gty',
'type3': 'qwe',
'type4': 'bbvdd',
'type5': 'zxczvdf'
};
I want to sort someObject by value, and this is where I have problem.
I have sorting function that should return key/value pairs sorted by value:
function SortObject(passedObject) {
var values = [];
var sorted_obj = {};
for (var key in passedObject) {
if (passedObject.hasOwnProperty(key)) {
values.push(passedObject[key]);
}
}
// sort keys
values.sort();
// create new object based on Sorted Keys
jQuery.each(values, function (i, value) {
var key = GetKey(passedObject, value);
sorted_obj[key] = value;
});
return sorted_obj;
}
and function to get key:
function GetKey(someObject, value) {
for (var key in someObject) {
if (someObject[key] === value) {
return key;
}
}
}
The problem is in last part when creating new, returning object - it's sorted by key again. Why? And this is specific situation when i have to operate on object NOT on array (yes I know that would be easier...)
Does anyone know how to sort items in object?
Plain objects don't have order at all. Arrays -that are a special types of objects- have.
The most close thing that you can have is an array with the object values sorted . Something like, for example:
_valuesOfAnObjectSorted = Object.keys(object).map(function(k){ return object[k]; }).sort();
You have two possibilities:
Refactor your object into an array
Something like this:
var myObj = [
['type1', 'abc'],
['type2', 'gty'],
...
];
Or even better, since using it somewhere would not rely on array positions but full named keys:
var myObj = [
{name: 'type1', val:'abc'},
{name: 'type2', val:'gty'},
...
];
Use your object with an auxiliar array
Wherever you want to use your object ordered by the keys, you can extract the keys as an array, order it and traverse it to access the object
var ordKeys = Object.keys(myObj).sort(); // pass inside a function if you want specific order
var key;
for (var i = 0, len = ordKeys.length; i < len; i +=1) {
key = ordKeys[i]
alert(key + " - " + myObj[key]);
}
Combination of both of them
If the object is not constructed by you, but comes from somewhere else, you can use the second option approach to construct an array of objects as in the first option. That would let you use your array anywhere with perfect order.
EDIT
You might want to check the library underscore.js. There you have extremely useful methods that could do the trick pretty easily. Probably the method _.pairs with some mapping would do all the work in one statement.

Underscore mapping an array's key to another

I want to map the keys of a large array into another key while removing the original key using Underscore.js' map() function.
large_array = _.map(data, function(element) {
element.b = element.a;
delete element.a;
return element;
});
console.log(large_array) // Returns an array with length == 0
Why would large_array have a length of zero?
I feel like I'm using the delete statement incorrrectly but I'm not sure.
Edit:
I may be abstracting this code too much, since simple runs seem to be working just fine.
The original data array is response from the FB.api('/me/friends', function(response) {...}
More specifically, it is an array of objects such as
{id: "12345", name: "Bubba Watson"}
As this is a response from Facebook, each object is guaranteed to have the 'id' attribute
The actual code is changing the the 'id' property to a 'facebook_id' property.
FB.api('/me/friends', function(response) {
console.log(response.data); // Returns 600+ Array of Bubba Watson like objects, each with an id.
large_array = _.map(response.data, function(element) {
element.facebook_id = element.id;
delete element.id;
return element;
});
console.log(large_array); // Mysteriously Returns: {length: 0, __proto__: Array[0]}
}
You're using delete correctly, however you may need to make sure:
data is indeed type Array and there are elements in data array
each element in the data array has property named a
Your code works for me: http://jsfiddle.net/EJTgx/
var data = [
{ a: 10 },
{ a: 20 },
{ a: 30 }
];
var large_array = _.map(data, function(element) {
element.b = element.a;
delete element.a;
return element;
});
console.log(large_array.length); // Returns 3

How to modify array?

I currently have an array of objects where each object has several properties. Example:
[
{ text: 'test1',
id: 1
},
{ text: 'test2',
id: 2
}
]
What would be the best way to convert this to an array of strings that contains the value from text? I had thought I might be able to do this using underscore.js:
headerText = _.pick(headerRow, 'text');
But I think that since the objects are in an array this will not work. My next idea is to just loop through each element in the array and push the text value to a new array, but i'm curious if anyone knows of a more elegant way to do this? Suggestions?
You're looking for Array#map:
var stringArray = headerRow.map(function(entry) {
return entry.text;
});
Live Example | Source
You don't even need Underscore, Array#map is part of ES5 and fully supported by V8, the JavaScript engine used by Node. Array#map calls the function you give it once for each entry in the array, and builds a new array from the return values of that function.
Or if you want to change the existing array, you can use Array#forEach:
headerRow.forEach(function(entry, index) {
headerRow[index] = entry.text;
});
Live Example | Source
Use _.map(headerRow, function(row) { return row.text; }). Array.map isn't available in IE < 9.
i'd use a foreach and just loop through it.
var jamie = [
{ text: 'test1',
id: 1
},
{ text: 'test2',
id: 2
}
];
var length = jamie.length,
element = [];
for (var i = 0; i < length; i++) {
element[i] = jamie[i].id;
// Do something with element i.
}
console.info(element);
This is a vanilla javascript version, which avoids using the not universally supported Array.map method.
// assign the array to a variable
var a = [
{ text: 'test1',
id: 1
},
{ text: 'test2',
id: 2
}
];
// loop through each item in the array, reassigning with it's text value
// not like this: for(i in a) a[i] = a[i].text
// but with a for loop based on the array length
var i;
for(i=a.length; i; i--){ a[i-1] = a[i-1].text; }
// check the results
console.log(a);
// ["test1", "test2"]

Categories

Resources