Find the name of an array containing object with certain property [duplicate] - javascript

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 7 years ago.
I've got an object which looks like this:
var myObject = {
array1: [
{id: "aaa"},
{id: "bbb"},
{id: 'ccc'}
],
array2: [
{id: "ddd"},
{id: "eee"},
{id: 'fff'}
],
childObject: {
property: "value"
}
};
What I need is a function that gets the name of an array with certain id value. For example:
getArrayName("myObject", "id", "eee") //returns "array2"
because it's always "id" it can be simplified to:
getArrayName("myObject", "ccc") //returns "array1"
I'm using lodash in this project, so I've tried .findKey(), but I can't get it to work.

Try this
function getArrayName(myObject, value)
{
for ( var arrayId in myObject)
{
var arr = global[ arrayId ];
for ( var counter = 0; counter < arr.length; counter++)
{
if ( arr[ counter ].id == value )
{
return arrayId ;
}
}
}
return "";
}

You can do this and also generalise the parameters you want to search by:
function getArrayName(objName, propKey, propVal) {
var obj = window[objName];
var resArray = _.find(obj, function (arr) {
return _.some(arr, function (arrObj) {
return arrObj[propKey] === propVal;
});
})
var index = 0;
for (var key in obj) {
if (obj[key] === resArray) {
index = key;
break;
}
}
return index;
}
getArrayName("myObject", "id", "ccc") //returns "array1"
Fiddle

Try this:
<script>
var myObject = {
array1: [
{id: "aaa"},
{id: "bbb"},
{id: 'ccc'}
],
array2: [
{id: "ddd"},
{id: "eee"},
{id: 'fff'}
],
childObject: {
property: "value"
}
};
function getArrayName(obj,id){
$.each(obj,function(key,value){
$.each(obj[key],function(key1,val){
if(val.id === id)
alert(JSON.stringify(obj[key]));
})
});
}
getArrayName(myObject,'eee');
</script>

Related

Perform .join on a complex object with array of object dynamically

I have a complex js object, that contains arrays of an object. The problem is some of the main object properties' arrays can have a different property.
var foo = {};
foo.prop1 = [
{name:"test", skill:1},
{name:"test2", skill:2},
];
foo.prop2 = [
{address:"Earth",distance:1},
{address:"Mars", distance:2}
]
My aim is to just replace the main object property value with the joined values for retrieval.
This is what I have right now.
if(Object.keys(foo).length){
Object.keys(foo).forEach(key => {
var x = foo[key];
if(key === "address") {
foo[key] = x.map(function(elem){return elem.address;}).join(";");
} else {
foo[key] = x.map(function(elem){return elem.name;}).join(";");
}
});
}
How can I make it dynamic so that I don't need to use the if statement? I just want to join all the first property of the inner obj.
Result:
foo new values would be:
foo.prop1 = test;test2
foo.prop2 = Earth;Mars
I got it. I just want to join the first property of the sub object.
I replaced the if with this
foo[key] = x.map(function(elem){return elem[Object.keys(elem)[0]]; }).join(";");
I guess you are trying to choose the value with string type
var foo = {};
foo.prop1 = [{
name: "test",
skill: 1
},
{
name: "test2",
skill: 2
},
];
foo.prop2 = [{
address: "Earth",
distance: 1
},
{
address: "Mars",
distance: 2
}
]
function formulate() {
const result = {};
(Object.keys(foo) || []).forEach(function(k) {
result[k] = foo[k].map(function(val) {
str_key = Object.keys(val).filter(function(val_k) {
return typeof val[val_k] === "string";
});
return str_key.map(function(s) {
return val[s];
});
}).join(";");
});
return result;
}
result = formulate()
console.log(result);
I hope, this will work for you
var foo = {};
foo.prop1 = [
{name:"test", skill:1},
{name:"test2", skill:2},
];
foo.prop2 = [
{address:"Earth",distance:1},
{address:"Mars", distance:2}
]
Object.keys(foo).forEach(key => {
foo[key]=foo[key].map(val => { return Object.entries(val)[0][1] } ).toString().split(",").join(";")
});
console.log(foo)

angularjs: check if value exists in array of objects

var a = [ { id:1}, {id:2} ];
var b = {id:1};
var res = a.indexOf(b._id) == -1;
console.log(res);
I want to check if b._id is in a[].
Note: a[] is an array of objects
Try this..
var a = [{ id:1}, {id:2}];
var b={id:1};
var arrayWithIds = a.map(function(x){
return x.id
}); // get new array contains all ids
var present = arrayWithIds.indexOf(b.id) != -1 // find the b.id array
console.log(present);
Here is the reference for Map and indexOf
This should work :
var a = [ { id:1} ,{id:2} ];
var b={id:1}
console.log(a.findIndex(function(obj){return obj.id=b.id}))
indexOf works when you are dealing with indexed arrays not with array of objects.
Please use the following code:
var a = [ { id:1}, {id:2} ];
var b={id:1}
function findMatch(element) {
return element.id === b.id;
}
console.log(a.findIndex(findMatch));
A better way is using .find function.
let a = [{
id: 1
}, {
id: 2
}],
b = {
id: 1
},
obj = a.find(function(itm) {
return itm.id == b.id;
});
console.log(obj)
And also using .findIndex function to get just index of item in array.
let a = [{
id: 1
}, {
id: 2
}],
b = {
id: 1
},
objIndex = a.findIndex(function(itm) {
return itm.id == b.id;
});
console.log(objIndex)
And for getting all objects with that condition use .filter function.
let a = [{
id: 1
}, {
id: 2
}],
b = {
id: 1
},
objArr = a.filter(function(itm) {
return itm.id == b.id;
});
console.log(objArr)
Array.map() function compare id and its value and return a Boolean value if map as commented by #Slava Utesinov
var a = [{id: 1}, {id: 2}];
var b = {id: 1};
if(a.map(x => x.id).indexOf(b.id) != -1){
console.log("Exists");
}else{
console.log("Not exists");
}
try this
var a = [ { id:1} ,{id:2} ];
var b={id:1}
console.log(a.find(x=>x.id==b.id))// return matched record
var a = [ { id:1} ,{id:2} ];
var b={id:3}
console.log(a.find(x=>x.id==b.id)) //return undefined
Use Array.map() function of JavaScript to check it. It will compare id and its value as well.
Below is working code:
var a = [{
id: 1
}, {
id: 2
}];
var b = {
id: 1
};
if (a.map(x => x.id).indexOf(b.id) != -1) {
console.log("Available");
} else {
console.log("Not available");
}
You can use Filter of AngularJS
var a = [{id:1}, {id:2}];
var b = {id:1};
var found = false;
var filterResult = $filter('filter')(a, {id: b.id}, true);
if (filterResult.length > 0) {
found = true;
}

how to use .include() method to check the value which is in a json inside array

I want to compare the value of a particular key in my JSON array with new value to check whether the value exists or not.
For example, I have an array:
[
{ name: abc, num: 121212 },
{ name: bcd, num: 21212 },
{ name: def, num: 111222 }
]
Now a new value comes which I want to check. Does that name already exist? If it does, then I only want to update the number and if not then I want to push the object in the array.
Here is my code:
if ((Dnum.num).includes(number)) {
console.log("inside if");
console.log(Dnum.indexOf(number));
} else {
Dnum.push({num:number,
lat:lat,
lng:lng,
name:name
});
}
Well, your problem (if I understand correctly) is that you want to use includes() but what you actually want to accomplish doesn't correspond to what the method does. You want to find if there's an object with a certain name in your array already, not if it contains a known element. Something like this:
var data = [{name: 'abc', num: 121212}, {name: 'bcd', num: 21212}, {name: 'def', num: 111222}];
function addOrUpdate(newElement, data) {
var i;
for (i = 0; i < data.length; i++) {
if (data[i].name == newElement.name) {
data[i] = newElement;
return;
}
}
data.push(newElement);
}
addOrUpdate({name: 'bcd', num: 131313}, data);
console.log(data);
addOrUpdate({name: 'new', num: 131313}, data);
console.log(data);
Problem:
Actually .includes() and .indexOf() methods won't work with objects, they should be used with an array of strings or Numbers as they use strict equality to compare the elements and objects can't be compared this way, so you need to implement this logic by yourself.
Solution:
You need to check if an object matching the searched name already exists in the array, update the num value of this object, otherwise if no object matches the searched name, push the new object to the array:
if (arr.some(function(obj) {
return obj.name === searchedVal.name;
})) {
arr.forEach(function(el, index) {
if (el.name === searchedVal.name) {
el.num += searchedVal.num;
found = true;
}
});
} else {
arr.push(searchedVal);
}
Demo:
var arr = [{
name: "abc",
num: 121212
}, {
name: "bcd",
num: 21212
}, {
name: "def",
num: 111222
}];
var searchedVal = {
name: "abc",
num: 5
};
if (arr.some(function(obj) {
return obj.name === searchedVal.name;
})) {
arr.forEach(function(el, index) {
if (el.name === searchedVal.name) {
el.num += searchedVal.num;
found = true;
}
});
} else {
arr.push(searchedVal);
}
console.log(arr);
If you don't want to use .some() method, you can do it this way:
var searchedVal = {
name: "abc",
num: 5
};
var found = false;
arr.forEach(function(el, index) {
if (el.name === searchedVal.name) {
el.num+= searchedVal.num;
found = true;
}
});
if (!found) {
arr.push(searchedVal);
}
Use Array.prototype.find():
var res = Dnum.find(function (item) {
return item.num === number;
});
if (res) {
console.log("inside if");
console.log(res);
res.num = number;
} else {
Dnum.push({
num:number,
lat:lat,
lng:lng,
name:name
});
}

Get parent array key in deep nested object using lodash

I'm using Lodash JavaScript library in my project and have a problem in getting the parent array key object filtered object:
I've the following data:
var data = {
5: [{
id: "3",
label: "Manish"
}, {
id: "6",
label: "Rahul"
}, {
id: "7",
label: "Vikash"
}],
8: [{
id: "16",
label: "Pankaj"
}, {
id: "45",
label: "Akash"
}],
9: [{
id: "15",
label: "Sunil"
}]
}
My requirement is if I've the array of [6,16] then I want a new result array containing values 5,8 because these two array keys have objects which contain id:"6" and id:"16"
I tried it using _.flatten and _.pick method but could not work. I used the following code;
var list = [];
_.each(data, function(item){
list.push(_.omit(item, 'id'));
list.push(_.flatten(_.pick(item, 'id')));
});
var result = _.flatten(list);
console.log(result);
var res = _([6, 16]).map(function(id){
return _.findKey(data, function(arr){
return _.some(arr, {id: new String(id)});
})
}).compact().uniq().value();
If simple javascript solution is okay with you then
var searchId=[6,16];
var newArr = [];
for ( key in data ){
data[key].forEach( function(innerValue){
if ( searchId.indexOf( Number(innerValue.id) ) != -1 ) newArr.push( key );
} );
}
console.log(newArr);
try this:
( hope im not missing some syntax )
var result = [];
var filterArray = [6,16];
_.each(filterArray, function(item){
_.merge(result,_.filter(data, function(o) { return _.contains(o,{id:item}) }));
});
Using _.pickBy this problem is solved simply:
var myArr = [6, 16]
var res = _.pickBy(data, function (value) {
return _(value).map('id').map(_.toNumber).intersection(myArr).size();
});
console.log(res)
https://jsfiddle.net/7s4s7h3w/

How do i remove an object in my case [duplicate]

This question already has answers here:
Remove array element based on object property
(12 answers)
Closed 8 years ago.
I am trying to remove an object based on the obj id.
I have something like
var array =[];
var id =3;
array [
{
id:'1',
title:'test'
},
{
id:'2',
title:'tes2'
},
{
id:'3',
title:'tes3'
}
]
How do I remove the object based on the id 3. thanks!
Use filter():
array = array.filter(
function( item ) {
return item.id != id;
}
);
Or, to modify the array in place:
for ( i = 0; i < array.length; ++i )
{
if (array[i].id == id)
{
array.splice(i, 1);
break;
}
}
As an alternative to the previously-posted answer, if you, or your users, are using an up-to-date browser, then the following is available:
function removeByPropertyEquals(haystack, needleProp, needleVal) {
haystack.forEach(function (obj, index) {
if (obj[needleProp] === needleVal) {
return index;
}
});
return -1;
}
var id = 3,
array = [{
id: '1',
title: 'test'
}, {
id: '2',
title: 'tes2'
}, {
id: '3',
title: 'tes3'
}];
console.log( array );
array.splice(removeByPropertyEquals(array, 'id', '3'), 1);
console.log( array );
JS Fiddle demo.
References:
Array.prototype.forEach().
Array.prototype.splice().

Categories