Javascript How to search in array by field [duplicate] - javascript

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 6 years ago.
I have a variable which holds this data:
{"main":[
{"id":"123","name":"name 1"},
{"id":"234","name":"name 2"}
]
}
I know the id of the data I want to search.
My question is...How do I search for the name of id 234 (for example) is thw data above?

Use Array#filter
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
var object = {
"main": [{
"id": "123",
"name": "name 1"
}, {
"id": "234",
"name": "name 2"
}]
};
var toFind = "234";
var filtered = object.main.filter(function(el) {
return el.id === toFind;
});
console.log(filtered);
If there is only one object in the array, for-loop with break could be preferred.
var object = {
"main": [{
"id": "123",
"name": "name 1"
}, {
"id": "234",
"name": "name 2"
}]
};
var toFind = "234";
for (var i = 0, len = object.main.length; i < len; i++) {
if (object.main[i].id === toFind) {
break;
}
}
console.log(object.main[i].name);

In ES5 environment, you could use Array#some, if you expect only one result.
var data = { "main": [{ "id": "123", "name": "name 1" }, { "id": "234", "name": "name 2" }] },
result;
data.main.some(function (a) {
if (a.id === '234') {
result = a;
return true;
}
});
console.log(result);
When you expect more than one result set, you may better use Array#filter
var data = { "main": [{ "id": "123", "name": "name 1" }, { "id": "234", "name": "name 2a" }, { "id": "234", "name": "name 2" }] },
result = data.main.filter(function (a) {
return a.id === '234';
});
console.log(result);
In ES6 environment, you could use Array#find for the first found element, but if there are more to find, then use Array#filter.
var data = { "main": [{ "id": "123", "name": "name 1" }, { "id": "234", "name": "name 2" }] },
result = data.main.find(a => a.id === '234');
console.log(result);

You can use find() if id's are unique.
var data = {"main":[
{"id":"123","name":"name 1"},
{"id":"234","name":"name 2"}
]
}
var name = data.main.find(function(o) {
return o.id == '234';
}).name;
console.log(name)

You can use Array.prototype.filter to find all matching elements and return them as a new array.
To find just the first match, you can use Array.prototype.find (ES2015+).

Related

Iterate array of objects with string array [duplicate]

This question already has answers here:
Filter array of objects based on another array in javascript
(10 answers)
Closed 2 years ago.
I have an array of objects (JAVASCRIPT) like below
[
{
"code": "123",
"label": "Test123"
},
{
"code": "234",
"label": "Test"
},
{
"code": "980",
"label": "joe"
}
]
And i have a string array like below
["123", "234"]
I want to loop through array of objects and pass string array to get the "label"
I am expecting an output like below
[
{
"code": "123",
"label": "Test123"
},
{
"code": "234",
"label": "Test"
}
]
Please let me know if there is any efficient solution (JAVASCRIPT) because my array of objects is big.
Try this:
const obj = [
{
"code": "123",
"label": "Test123"
},
{
"code": "234",
"label": "Test"
},
{
"code": "980",
"label": "joe"
}
];
const arr = ["123", "234"];
var output = arr.flatMap(item => obj.filter(x => x.code == item));
console.log(output);
If the array is big, this can help to use Array.reduce.
const input = [{
"code": "123",
"label": "Test123"
},
{
"code": "234",
"label": "Test"
},
{
"code": "980",
"label": "joe"
}
]
const input2 = ["123", "234"];
const inputObj =input.reduce((acc, cur) => {
acc[cur.code] = cur.label;
return acc;
}, {});
const result = input2.reduce((acc, cur) => {
if (inputObj[cur]) {
acc.push({
code: cur,
label: inputObj[cur]
});
}
return acc;
}, []);
console.log(result);

Find nested object based on a parameter in Javascript

I have an array which looks like this:
[
{
"boxes": [
{
"id": 2,
"content": {
"name": "ABC",
"details": "some details for abc"
}
}
]
},
{
"boxes": [
{
"id": 3,
"content": {
"name": "XYZ",
"details": "some details for xyz"
}
},
{
"id": 4,
"content": {
"name": "UVW",
"details": "some details for uvw"
}
}
]
},
{}
]
And I have a variable: let id = 3
I want to be able to search through the nested array "boxes" to find the content property of the object that have the given id. Such that the result is:
{
"name": "XYZ",
"details": "some details for xyz"
}
Till now I have gathered that I can use a combination forEach and .filter do find this. But I'm not sure how. Also, I have control over the original data. So, if there's a better way to store the original data, I will be glad to have suggestions.
Actually I did attempt but got stuck:
Let's say the original array is called house.
let matches = []
let id = 3
house.forEach(function(e) {
matches = matches.concat(e.boxes.filter(function(b) {
return (b.id === id);
}));})
console.log(matches[0].content)
You could use map method by passing a callback function as argument. The scope of map method is to get all items from boxes array.
Also, I'm using filter(Boolean) statement in order to remove undefined value for those items which doesn't have boxes as property.
At least, use find method in order to get the desired output result.
let arr = [ { "boxes": [ { "id": 2, "content": { "name": "ABC", "details": "some details for abc" } } ] }, { "boxes": [ { "id": 3, "content": { "name": "XYZ", "details": "some details for xyz" } }, { "id": 4, "content": { "name": "UVW", "details": "some details for uvw" } } ] }, {} ]
let id = 1;
let result = [].concat(...arr.map(item => item.boxes))
.filter(Boolean)
.find(({id}) => id == id).content;
console.log(result);
First you need to put boxes object into one array, it seems it just has couple extra levels you don't need; You can create a helper function for that.
make a loop with if statement if there is what you are looking for or not
Here I use forEach() to loop through the data and get the boxes.
After that, I use filter() to get the object with the desired id. That's all.
const data = [
{
"boxes": [
{
"id": 2,
"content": {
"name": "ABC",
"details": "some details for abc"
}
}
]
},
{
"boxes": [
{
"id": 3,
"content": {
"name": "XYZ",
"details": "some details for xyz"
}
},
{
"id": 4,
"content": {
"name": "UVW",
"details": "some details for uvw"
}
}
]
},
{}
]
data.forEach(data => {
if (data.boxes){
let searchedData = data.boxes.filter(box => box.id == 3);
if (searchedData.length > 0){
console.log(searchedData[0].content);
}
}
});

Comparing arrays of objects and remove duplicate [duplicate]

This question already has answers here:
Remove duplicates in an object array Javascript
(10 answers)
Closed 5 years ago.
I have an array containing arrays of objects which I need to compare.
I've looked through multiple similar threads, but I couldn't find a proper one that compares multiple arrays of objects (most are comparing two arrays of objects or just comparing the objects within a single array)
This is the data (below is a JSFiddle with code sample)
const data = [
[
{
"id": "65",
"name": "Some object name",
"value": 90
},
{
"id": "89",
"name": "Second Item",
"value": 20
}
],
[
{
"id": "89",
"name": "Second Item",
"value": 20
},
{
"id": "65",
"name": "Some object name",
"value": 90
}
],
[
{
"id": "14",
"name": "Third one",
"value": 10
}
]
]
I want to remove all duplicate arrays of objects, regardless of the length of data (there could be a lot more records).
I managed to get the unique ones extracted into an object:
const unique = data.reduce(function(result, obj) {
return Object.assign(result, obj)
}, [])
That doesn't work for me though, because I need 1 of the duplicated arrays to remain and the returned data to be an array as well, instead of an object. E.g.:
// result I need
[
[
{
"id":"65",
"name":"Some object name",
"value":90
},
{
"id":"89",
"name":"Second Item",
"value":20
}
],
[
{
"id":"14",
"name":"Third one",
"value":10
}
]
]
So how do I compare each array of objects to the others in the parent array and preserve one of each duplicated or unique array of objects?
JSFiddle
you can achieve so by using function.As below. Not sure about best optimum way of doing so.
var testArray = [
[
{
"id": "65",
"name": "Some object name",
"value": 90
},
{
"id": "89",
"name": "Second Item",
"value": 20
}
],
[
{
"id": "89",
"name": "Second Item",
"value": 20
},
{
"id": "65",
"name": "Some object name",
"value": 90
}
],
[
{
"id": "14",
"name": "Third one",
"value": 10
}
]
]
function removeDuplicatesFromArray(arr){
var obj={};
var uniqueArr=[];
for(var i=0;i<arr.length;i++){
if(!obj.hasOwnProperty(arr[i])){
obj[arr[i]] = arr[i];
uniqueArr.push(arr[i]);
}
}
return uniqueArr;
}
var newArr = removeDuplicatesFromArray(testArray);
console.log(newArr);
const data = [
[
{
"id": "65",
"name": "Some object name",
"value": 90
},
{
"id": "89",
"name": "Second Item",
"value": 20
}
],
[
{
"id": "89",
"name": "Second Item",
"value": 20
},
{
"id": "65",
"name": "Some object name",
"value": 90
}
],
[
{
"id": "14",
"name": "Third one",
"value": 10
}
]
];
const temp = {};
const result = [];
data.forEach(itemArr => {
const items = itemArr.filter(item => {
const isUnique = temp[`${item.id}-${item.name}-${item.value}`] === undefined;
temp[`${item.id}-${item.name}-${item.value}`] = true;
return isUnique;
});
if (items.length !== 0)
result.push(items);
});
console.log(result);

Update List base on another list in JavaScript

How Can I update an Array based on another Array?
This is how I tried to do:
var ref = [
{
"name": "Jack",
"title": "Manager",
"description": "",
},
{
"name": "Steve",
"title": "CEO",
"description": "A test description",
}
];
var elem = [
{
"name": "Jack",
"title": "Manager",
"description": "",
},
{
"name": "Steve",
"title": "CEO",
"description": "A test description",
}
];
for (var i = 0; i < ref.length; i++) {
ref.indexOf(elem[i]) === -1 ? ref.push(elem[i]) : console.log("This item already exists");
}
console.log(ref);
console.log(elem);
This Loop caused an error because the length is changing after each iterate.
What I want is, to add each element from elem object if it doesn't exist in arr object and of course stays in JOSN format. In my example, it doesn't have to change.
It would be better to run the loop over elem. Also you can't compare objects like that because references will differ, so you will have to do deep check, something like this should work:
var ref = [
{
"name": "Jack",
"title": "Manager",
"description": "",
},
{
"name": "Steve",
"title": "CEO",
"description": "A test description",
}
];
var elem = [
{
"name": "Jack",
"title": "Manager",
"description": "",
},
{
"name": "Steve",
"title": "CEO",
"description": "A test description",
}
];
for (var i = 0; i < elem.length; i++) {
var found = false;
for (var j=0; j<ref.length; j++){
var count = Object.keys(elem[i]).length;
for(var key in elem[i]){
if(ref[j][key] === elem[i][key])
count--;
}
if (count === 0){
found= true;
break;
}
}
if (!found)
ref.push(elem[i]);
}
console.log(ref);
console.log(elem);
To avoid nested loops, you could build a Set with each of the keys that you have in ref. Let's say you consider the name to be the identifying key, then it would look like this:
ref = ref.concat(elem.filter(function (o) {
return !this.has(o.name)
}, new Set(ref.map(o => o.name))));
So, this builds the Set by taking all the names in ref, passes that as this to a filter callback, which checks for each elem entry whether it has a name that is in the set. If so, it is excluded by the filter. This filtered result is concatenated to ref.
If your identifying key is something else, like the combination name and title, then adjust the function that is used in the last map(.......), and apply the same logic in has().
Here is a fiddle (with slightly different sample data) that uses the combination of name and title as identifying key:
var ref = [{
"name": "Jack",
"title": "Manager",
"description": "",
}, {
"name": "Steve",
"title": "CEO",
"description": "A test description",
}];
var elem = [{
"name": "Jack",
"title": "Manager",
"description": "",
}, {
"name": "Steve",
"title": "Programmer",
"description": "Java addict",
}];
ref = ref.concat(elem.filter(function (o) {
return !this.has(JSON.stringify([o.name, o.title]))
}, new Set(ref.map(o => JSON.stringify([o.name, o.title])))));
console.log(ref);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Javascript Map getting values of sub in return

I am having an issue returning data from a mapping.
Here is the data:
{
"id": "123",
"name": "name here",
"description": "a desc here"
"parts": [
{
"id": "432",
"name": "part name",
"stats": {
"count": 4,
},
"description": ""
},
etc....
And here's the current code:
var result = myData.map(function(value){
return [value.name, 1];
});
What I want to do it to get the count so I tried:
var result = myData.parts.map(function(value){
return [value.name.stats.count, 1];
});
But it's not returning the value of it.
What I'm I doing wrong?
You could map parts for getting the counts in an array.
counts = data.parts.map(function (o) {
return o.stats.count;
});

Categories

Resources