How to find the name property from an array of Objects - javascript

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

Related

Searching array with multiple keys

I can see this works fine for searching a simple array:
var arr1 = ['a','b','c','d','e'];
var index1 = arr1.indexOf('d');
console.log("index1:" + index1); // index1:3
When I try to do the same thing for a different kind of array, it doesn't find the "jane" value:
var arr2 = [{"id":0,"name":"petty"},{"id":1,"name":"jane"},{"id":2,"name":"with"}];
var index2 = arr2.indexOf('jane');
console.log("index2:" + index2); // index2:-1
Sorry - I realise I am probably missing something obvious. I have searched on SO / google for searching multi dimensional arrays, but I don't even know if the array in the 2nd example is a 2d / multi dimensional array, so I am probably not searching for the right thing.
You can use findIndex() method to find index of object with specific value.
var arr = [{"id":0,"name":"petty"},{"id":1,"name":"jane"},{"id":2,"name":"with"}];
var index = arr.findIndex(e => e.name == 'jane')
console.log("index: " + index);
First of all: it's not a multi-dimensional array. It's an array consisting of objects. It's one-dimensional. To find an object you need to iterate through an array and check the needed key, e.g.:
arr.findIndex(function(el) { return el.name === 'jane' })
You could check all values of the objects and use Array#findIndex instead of Array#indexOf.
var arr2 = [{ id: 0, name: "petty" }, { id: 1, name: "jane" }, { id: 2, name: "with" }],
index2 = arr2.findIndex(o => Object.values(o).some(v => v === 'jane'));
console.log(index2);
var arr = [{"id":0,"name":"petty"},{"id":1,"name":"jane"},{"id":2,"name":"with"}];
arr.findIndex((item)=>{return item.name=="petty"})
//output is 0

which function to use in order to remove an object from an array

I have an array of objects that I'm trying to loop through to match for a specific value, if found delete that object else return false. Below is the code:
array: [{
obj1:{
id: null,
name:'test',
address: '6857346jfhbdjshb'
},
obj12:{
id: 678346,
name:'test',
address: '63784hgj'
},
obj13:{
id: null,
name:'test',
address: 'tevhgvd'
},
obj15:{
id: 65847,
name:'test',
address: 'djhvwe677ghdgv'
},
obj18:{
address: ""
}
}]
js:
for (var obj in array){
if (array[obj].address === "63784hgj" || array[obj].address === "djhvwe677ghdgv" ||array[prop].address === "")
{
array[obj].destroy(); //equivalent to array[1].destroy() (destroy, delete,remove,hide, pop none of them work)
}
}
I'm not sure which function is the correct one to remove object from array.
You apparently want to filter out certain properties from the single element of your array, which is an object, containing subobjects, when the address property of the subobject matches one or more string values.
Extract the first element of the array, then loop over its properties with a for...in loop. If the subproperty matches, delete the property with delete.
function filterproc(array) {
var o = array[0];
for (var k in o)
if (o[k].address === "....")
delete o[k];
}
To match against multiple possibilities, consider using indexOf, which checks if an array contains some value:
if (['63784hgj', ...].indexOf(o[k]) !== -1) ...
If what you want is what toranaburo described in his answer then nothing to do with mine. :( (inform me to delete mine)
If you want a function which returns the new value do this:
var forbiddenAddressList = ['', '63784hgj', 'djhvwe677ghdgv'];
var newArray = myArray.filter(i => forbiddenAddressList.indexof(i.address) === -1);
another way:
var newArray = [];
for (var i = 0; i < myArray.length; i++)
if(forbiddenAddressList.indexof(i.address) === -1)
newArray.push(myArray[i]);
So if what you're asking is to loop through an array of objects, and if the value of a property is found then delete the object it belongs to, then this is what I came up with.
var array = [
{id: null,name:'test',address: '6857346jfhbdjshb'},
{id: 678346,name:'test',address: '63784hgj'},
{id: null,name:'test',address: 'tevhgvd'},
{id: 65847,name:'test',address: 'djhvwe677ghdgv'},
{address: ""}
];
for (var obj in array){
if (array[obj].address === "63784hgj" || array[obj].address === "djhvwe677ghdgv" || array[obj].address === "")
{
array.splice(obj, 1);
}
}
I modified your array of objects, but everything except Obj1, Obj2 etc. remains because arrays are already indexed, thus array[0] refers to Obj1. Also in your if statement you had array[prop] which is undefined, so be sure to change it in your code. This worked for what I think you were trying to do, so let me know if it helps.

Remove a record in a Object Array jQuery

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);
}

An object contains a collection of objects - each with an id and name, how do I separate them?

At the moment I have this object:
obj = [object{id: 1, name: test, parentID: 3}, object{id:1, name: another, parentID: 5}, object{id:2, name:something, parentID: 1}].
Ultimately I want an object structured in a different manner.
So that it is object, but if my identifier is 1, it has a collection of names (in this case test, and another). If it is 2, it only shows 'something'.
I can't work out how this should look, probably like so?
obj = [[1,test], [1,another], [2,something]] right?
So that if I call obj[1] I get a multiples back (test, another etc).
Can someone help? I've been fiddling with this for an hour now, I just don't understand.
I built the original object like this:
var obj = Array();
//loop here
var obj = {
id: id,
name: name,
parentID: parentID
};
obj.push(obj);
What did I do wrong? How can I fix this? This got me my object within objects thing, but really I want id's and names within id's and names. My ultimate goal is to iterate through this. So that I only get out the names of anything of a like ID, that way I can use this to populate an array or count
Thus:
if(obj[id] == 1){
//put the name in the new array
}
is my ultimate goal. But I've gotten a bit lost with the initial object creation so now it is a big mess.
Try:
var obj = [{id: 1, name: "Foo"}, {id: 2, name: "Fee"}, {id: 3, name: "Fii"}];
var result = [], item, i = 0;
while(item = obj[i++]){
for(key in item){
if(key === "id") continue; //remove this line if you want to keep the ID also in the array
!result[i] && (result[i] = []);
result[i].push(item[key]);
}
}
console.log(result[1]); // --> ["Foo"]
My take:
var sourceObject=[{id:0,name:'Tahir'},{id:0,name:'Ahmed'},{id:1,name:'David'},{id:1,name:'G'},{id:2,name:'TA'},{id:3,name:'DG'}];
function getNames(id){
var names=[],length=sourceObject.length,i=0;
for(i;i<length;i+=1){
if(sourceObject[i].id===id){
names[names.length]=sourceObject[i].name;
}
}
return names;
}
console.log(getNames(1));
What you want to do is walk the array of objects one time. Each time through, you want to check your new object to see if that id exists yet. If it does, add the name. If not, make a new entry for that id and add an array with one entry. Note, this doesn't handle duplicate names (it just adds it again).
var array = [{id:1, name:"test"},
{id:1, name:"another"},
{id:2, name:"something"}];
var result = {};
array.forEach(function(item) {
if (result[item.id]) {
result[item.id].push(item.name);
}
else {
result[item.id] = [item.name];
}
});
console.log(result[1]);

Get a list of objects that have the same value for a specific property

I have a bunch of objects that have a .type property assigned them.
All the objects are in an array like this:
var arr = [];
arr[0] = {'type':1,'x':56,'y':2};
arr[1] = {'type':2,'x':1, 'y':23};
arr[2] = {'type':1,'x':23,'y':63};
What i would like to do is return a list of all the objects that have for example type == 1.
Is there any built in way to do or will I have to iterate each one individually and push those that match to a new array?
If iterating all the n elements in the array is of concern, then you could construct your data structure as an object and not an array:
var multimap = {};
multimap[1] = [{'type':1,'x':56,'y':2},{'type':1,'x':23,'y':63}];
multimap[2] = [{'type':2,'x':1, 'y':23}];
and you can retrieve the elements of a particular type in order of 1, like:
multimap[1] will give you the elements of type 1.
Inserting a new element of a particular type into the arr structure:
if(!multimap[type]){
multimap[type] = [];
}
multimap[type].push(element);
in js 1.6 you can use the filter function like so:
var result = arr.filter(function(o){return o.type == 1})
...instead of creating and pushing to a new array inside a for loop
technically both of them do the same thing, but filter is elegant as it abstracts the ugliness
Use the .filter function of the array:
var arr = [{
'type': 1,
'x': 56,
'y': 2
}, {
'type': 2,
'x': 1,
'y': 23
}, {
'type': 1,
'x': 23,
'y': 63
}];
var filtered = arr.filter(function(obj) {
return obj.type === 1;
})
for(i=0;i = arr.length;i++){
if (arr[i].hasOwnProperty('type')) {
alert('have key!');
}
}
Using this you can search any property not just type . If you pass property name as parameter
You can achieve this using the .filter() function in Javascript.
Working Code Snippet:
var arr = [];
arr[0] = {'type':1,'x':56,'y':2};
arr[1] = {'type':2,'x':1, 'y':23};
arr[2] = {'type':1,'x':23,'y':63};
var filteredArr = arr.filter(function(obj) {
return obj.type === 1; // filter the objects with type 1
});
console.dir(filteredArr); // check your console
Readup:
.filter() | MDN
EDIT:
As mentioned by #c.P.u1, the filter iterates the array internally. If you think from the algorithmic point of view, you will have to iterate over the data to filter something out.

Categories

Resources