convert integer to array of object. - javascript

var items = [
{ "id": 1, "label": "Item1" },
{ "id": 2, "label": "Item2" },
{ "id": 3, "label": "Item3" }
];
I have this array of objects named 'items'. I get itemselected = 3 from the database.
I need to convert this 3 into the following form.
0:Object
id:3
label:"Item3"
Similarly, if i have a value 2 coming from the database, i should convert it to
0:Object
id:2
label:"Item2"
Can anyone please let me hint of how to get it solved. i am not here to get the answer. These questions are quite tricky for me and i always fail to get the logic right. Any advice on how to master this conversions will be of great help. thanks.

Since you tagged underscore.js, this should be very easy:
var selectedObject = _.findWhere(items, {id: itemselected});
Using ECMA6, you can achieve the same using .find method on arrays:
let selectedObject = items.find(el => el.id === itemselected);
With ECMA5, you can use filter method of arrays. Be careful that filter returns undefined if no element has been found:
var selectedObject = items.filter(function(el) { return el.id === itemselected});

Use jquery $.map function as below
$.map(item, function( n, i ) { if(n["id"] == 3) return ( n );});

Based on the title of your question: «convert integer to array of object». You can use JavaScript Array#filter.
The filter() method creates a new array with all elements that
pass the test implemented by the provided function.
Something like this:
var items = [{
"id": 1,
"label": "Item1"
},
{
"id": 2,
"label": "Item2"
},
{
"id": 3,
"label": "Item3"
}
];
var value = 2;
var result = items.filter(function(x) {
return x.id === value;
});
console.log(result); // Prints an Array of object.

Try this
var obj = {} ;
items = [
{ "id": 1, "label": "Item1" },
{ "id": 2, "label": "Item2" },
{ "id": 3, "label": "Item3" }
];
items.map(function(n) { obj[n.id] = n });

Related

Array element comparison with Json response in Javascript

I have a Json response which looks like this.
[
{
"name": "name1",
"id": "1"
},
{
"name": "name2",
"id": "2"
},
{
"name": "name4",
"id": "4"
},
{
"name": "name5",
"id": "5"
}
]
I have another array called "a" which has only id [1,2,3,4,5]. Now i have to compare every element in the array with json response object id. For example, the first element of array "a" exists in json response object , then its respective name should be retrieved and stored in another new array called "b" -> [name1]. The second element of array "a" exists in json response object , then its respective name should be retrieved and appended in "b" array -> [name1,name2]. The third element of array "a" does not exists in json response object , hence no name. In this case, Instead of name, "0" should be appedned in b array for that id -> [name1,name2,0]. The fourth element of array "a" exists in json response object , then its respective name should be retrieved and appended in b array -> [name1,name2,0,name4]. The fifth element of array "a" exists in json response object , then its respective name should be retrieved and appended in b array -> [name1,name2,0,name4,name5].
I tried to implement this by the following code. But instead of [name1,name2,0,name4,name5] , I am getting [name1,name2,name4,name5,0]
for (var i = 0; i < a.length; i++) {
if (a.includes(jsonResponse[i].id)) {
b.push(jsonResponse[i].name);
}
else{
b.push("0");
}
}
You need to search for each element of b in the entire jsonResponse array, not just test the current index of jsonResponse.
Use .find() to find the element with the ID you're looking for.
let jsonResponse = [{
"name": "name1",
"id": "1"
},
{
"name": "name2",
"id": "2"
},
{
"name": "name4",
"id": "4"
},
{
"name": "name5",
"id": "5"
}
];
let a = [1, 2, 3, 4, 5];
let b = a.map(id => {
let found = jsonResponse.find(u => u.id == id);
return found ? found.name : "0";
});
console.log(b);
You can use Map collection to have O(1) while accessing to the desired element when you map your elements:
let mapResponse = new Map(jsonResponse.map(s=> [+s.id, s.name]));
const result = a.map(id => mapResponse.get(id) || '0')
An example:
let jsonResponse = [
{
"name": "name1",
"id": "1"
},
{
"name": "name2",
"id": "2"
},
{
"name": "name4",
"id": "4"
},
{
"name": "name5",
"id": "5"
}
];
let a = [1, 2, 3, 4, 5];
let mapResponse = new Map(jsonResponse.map(s=> [+s.id, s.name]));
const result = a.map(id => mapResponse.get(id) || '0')
console.log(result);

Add json Elements and values to Multiple json objects

I want combine a JSON object to an ARRAY.
I would like retrieve data from keys finded on var product, and combine score finded to a new variable ( combined results )
combinedresults is what I need. I absolutely don't know how to do this
var product = {
"presentation": 3,
"imgmax": http://test.com/img.jpg,
"puissance": 5,
"efficacite": 4,
"description": "This product is awesome but i need to combine JSON results"
}
var array = [
{
"caracname": "presentation",
"name": "Présentation"
},
{
"caracname": "efficacite",
"name": "Efficacité"
},
{
"caracnam": "puissance",
"name": "Puissance"
}
]
var combinedresults = [
{
"caracname": "presentation",
"name": "Présentation",
"score": 3
},
{
"caracname": "efficacite",
"name": "Efficacité",
"score": 4
},
{
"caracnam": "puissance",
"name": "Puissance",
"score": 5
}
]
Iterate through each item of the array, if the product object contains a key that matches the current items caracname, add it's value as a score.
See below:
var product = {
"presentation": 3,
"imgmax": "http://test.com/img.jpg",
"puissance": 5,
"efficacite": 4,
"description": "This product is awesome but i need to combine JSON results"
}
var array = [
{
"caracname": "presentation",
"name": "Présentation"
},
{
"caracname": "efficacite",
"name": "Efficacité"
},
{
"caracname": "puissance",
"name": "Puissance"
}
]
array.forEach(function(item) {
if (product[item.caracname]) {
item.score = product[item.caracname];
}
});
console.log(array);
Simply map over your current array, extending every object with the score attribute.
array.map(obj => ({...obj, score: product[obj.caracname]}));
If you are not familiar, consider having a look at the spread operator;

Compare array of objects to array of ids

Using jQuery, I would like to use an array of ids to find the objects inside the allObjects array that have the matching Id value.
var arrayOfIds = [1, 4, 5];
var allObjects = [{"Id":"1", "name":"aa"},{"Id":"2", "name":"bb"} ,{"Id":"3", "name":"cc"} ,{"Id":"4", "name":"dd"}, {"Id":"5", "name":"ee"}, {"Id":"6", "name":"ff"}, {"Id":"7", "name":"gg"}, {"Id":"8", "name":"hh"}, {"Id":"9", "name":"ii"}];
The result would equal:
[{"Id":"1", "name":"aa"}, {"Id":"4", "name":"dd"}, {"Id":"5", "name":"ee"}]
So far, I can only use the following to extract an individual object:
var result = $.grep(arrayOfIds, function(e) { return e.Id == 3; });
I feel as though the answer might be achieved by amending the above $.grep query somehow but can't figure it out.
You don't need jQuery for this. You can use Array.prototype.filter() to filter allObjects and Array.prototype.includes() to check if the objects Id property is in arrayOfIds:
allObjects.filter(x=> arrayOfIds.includes(Number(x.Id)))
See demo on JS Bin.
Best is you transform the array to an object itself:
function atoo(a)
{
var i, obj;
obj = {};
for (i = 0; i < a.length; i++)
{
obj[a[i].Id] = a[i];
}
return obj;
}
You can now access all items in the array through the object by simply addressing them as an index:
obj["4"]
returns the correct object that is also stored in the array under a[3].
There is no jQuery involved which should be considered a feature because it is a general solution to all kinds of these problems.
Using a filter (as in Array.prototype.filter()) is easier to write but also incurs in performance problems when you access the items very often or the array is very large. The above solution relies on the internal implementation of the object referencing which is as fast as you can wish for.
You can use filter() method like following.
var arrayOfIds = [1, 4, 5];
var allObjects = [{ "Id": "1", "name": "aa" }, { "Id": "2", "name": "bb" }, { "Id": "3", "name": "cc" }, { "Id": "4", "name": "dd" }, { "Id": "5", "name": "ee" }, { "Id": "6", "name": "ff" }, { "Id": "7", "name": "gg" }, { "Id": "8", "name": "hh" }, { "Id": "9", "name": "ii" }];
var result = $(allObjects).filter(function() { return arrayOfIds.indexOf(+this.Id) > -1 }).get();

Filter Array Not in Another Array

Need to filter one array based on another array. Is there a util function in knock out ? else i need to go with javascript
First :
var obj1 = [{
"visible": "true",
"id": 1
}, {
"visible": "true",
"id": 2
}, {
"visible": "true",
"id": 3
}, {
"Name": "Test3",
"id": 4
}];
Second :
var obj2 = [ 2,3]
Now i need to filter obj1 based on obj2 and return items from obj1 that are not in obj2 omittng 2,3 in the above data (Comparison on object 1 Id)
output:
[{
"visible": "true",
"id": 1
}, {
"Name": "Test3",
"id": 4
}];
You can simply run through obj1 using filter and use indexOf on obj2 to see if it exists. indexOf returns -1 if the value isn't in the array, and filter includes the item when the callback returns true.
var arr = obj1.filter(function(item){
return obj2.indexOf(item.id) === -1;
});
With newer ES syntax and APIs, it becomes simpler:
const arr = obj1.filter(i => !obj2.includes(i.id))
Even if the answer provided by #Joseph are good, it can lead to performance issues if you have a very large array. The complexity is O(n^2), but it can be improved to O(n). Below I put the code I'd use to perform this task:
//create a map for storing object id
const map = new Map();
//add existing id from the array to the map
for (item of obj2) {
map.set(item.id, true);
}
//create a new array that contains all items that aren't included in the //map
//the map lookUp is O(1) complexity
const arr = obj1.filter(item => !map[item.id]);
In this way we avoid nested iteration and have O(n) complexity
To create your output array, create a function that will iterate through obj1 and populate a new array based on whether the id of every obj in the iteration exists in obj2.
var obj1 = [{
"visible": "true",
"id": 1
}, {
"visible": "true",
"id": 2
}, {
"visible": "true",
"id": 3
}, {
"Name": "Test3",
"id": 4
}];
var obj2 = [2,3]
var select = function(arr) {
var newArr = [];
obj1.forEach(function(obj) {
if obj2.indexOf(obj.id) !== -1 {
newArr.push(obj)
};
};
return newArr;
};

Get specific object by id from array of objects in AngularJS

I have a JSON file containing some data I d like to access on my AngularJS website. Now what I want is to get only one object from the array. So I d like for example Item with id 1.
The data looks like this:
{ "results": [
{
"id": 1,
"name": "Test"
},
{
"id": 2,
"name": "Beispiel"
},
{
"id": 3,
"name": "Sample"
}
] }
I'd like to load the data with AngularJS $http functionality like this:
$http.get("data/SampleData.json");
which is working. But how can I now get a specific data object (by id) from the array I get from $http.get ?
Using ES6 solution
For those still reading this answer, if you are using ES6 the find method was added in arrays. So assuming the same collection, the solution'd be:
const foo = { "results": [
{
"id": 12,
"name": "Test"
},
{
"id": 2,
"name": "Beispiel"
},
{
"id": 3,
"name": "Sample"
}
] };
foo.results.find(item => item.id === 2)
I'd totally go for this solution now, as is less tied to angular or any other framework. Pure Javascript.
Angular solution (old solution)
I aimed to solve this problem by doing the following:
$filter('filter')(foo.results, {id: 1})[0];
A use case example:
app.controller('FooCtrl', ['$filter', function($filter) {
var foo = { "results": [
{
"id": 12,
"name": "Test"
},
{
"id": 2,
"name": "Beispiel"
},
{
"id": 3,
"name": "Sample"
}
] };
// We filter the array by id, the result is an array
// so we select the element 0
single_object = $filter('filter')(foo.results, function (d) {return d.id === 2;})[0];
// If you want to see the result, just check the log
console.log(single_object);
}]);
Plunker: http://plnkr.co/edit/5E7FYqNNqDuqFBlyDqRh?p=preview
For anyone looking at this old post, this is the easiest way to do it currently. It only requires an AngularJS $filter. Its like Willemoes answer, but shorter and easier to understand.
{
"results": [
{
"id": 1,
"name": "Test"
},
{
"id": 2,
"name": "Beispiel"
},
{
"id": 3,
"name": "Sample"
}
]
}
var object_by_id = $filter('filter')(foo.results, {id: 2 })[0];
// Returns { id: 2, name: "Beispiel" }
WARNING
As #mpgn says, this doesn't work properly. This will catch more results. Example: when you search 3 this will catch 23 too
personally i use underscore for this kind of stuff... so
a = _.find(results,function(rw){ return rw.id == 2 });
then "a" would be the row that you wanted of your array where the id was equal to 2
I just want to add something to Willemoes answer.
The same code written directly inside the HTML will look like this:
{{(FooController.results | filter : {id: 1})[0].name }}
Assuming that "results" is a variable of your FooController and you want to display the "name" property of the filtered item.
You can use ng-repeat and pick data only if data matches what you are looking for using ng-show
for example:
<div ng-repeat="data in res.results" ng-show="data.id==1">
{{data.name}}
</div>
You can just loop over your array:
var doc = { /* your json */ };
function getById(arr, id) {
for (var d = 0, len = arr.length; d < len; d += 1) {
if (arr[d].id === id) {
return arr[d];
}
}
}
var doc_id_2 = getById(doc.results, 2);
If you don't want to write this messy loops, you can consider using underscore.js or Lo-Dash (example in the latter):
var doc_id_2 = _.filter(doc.results, {id: 2})[0]
If you want the list of items like city on the basis of state id then use
var state_Id = 5;
var items = ($filter('filter')(citylist, {stateId: state_Id }));
Unfortunately (unless I'm mistaken), I think you need to iterate over the results object.
for(var i = 0; i < results.length; i += 1){
var result = results[i];
if(result.id === id){
return result;
}
}
At least this way it will break out of the iteration as soon as it finds the correct matching id.
Why complicate the situation? this is simple write some function like this:
function findBySpecField(data, reqField, value, resField) {
var container = data;
for (var i = 0; i < container.length; i++) {
if (container[i][reqField] == value) {
return(container[i][resField]);
}
}
return '';
}
Use Case:
var data=[{
"id": 502100,
"name": "Bərdə filialı"
},
{
"id": 502122
"name": "10 saylı filialı"
},
{
"id": 503176
"name": "5 sayli filialı"
}]
console.log('Result is '+findBySpecField(data,'id','502100','name'));
output:
Result is Bərdə filialı
The only way to do this is to iterate over the array. Obviously if you are sure that the results are ordered by id you can do a binary search
$scope.olkes = [{'id':11, 'name':'---Zəhmət olmasa seçim edin---'},
{'id':15, 'name':'Türkyə'},
{'id':45, 'name':'Azərbaycan'},
{'id':60, 'name':'Rusya'},
{'id':64, 'name':'Gürcüstan'},
{'id':65, 'name':'Qazaxıstan'}];
<span>{{(olkes | filter: {id:45})[0].name}}</span>
output: Azərbaycan
If you can, design your JSON data structure by making use of the array indexes as IDs. You can even "normalize" your JSON arrays as long as you've no problem making use of the array indexes as "primary key" and "foreign key", something like RDBMS. As such, in future, you can even do something like this:
function getParentById(childID) {
var parentObject = parentArray[childArray[childID].parentID];
return parentObject;
}
This is the solution "By Design". For your case, simply:
var nameToFind = results[idToQuery - 1].name;
Of course, if your ID format is something like "XX-0001" of which its array index is 0, then you can either do some string manipulation to map the ID; or else nothing can be done about that except through the iteration approach.
I know I am too late to answer but it's always better to show up rather than not showing up at all :). ES6 way to get it:
$http.get("data/SampleData.json").then(response => {
let id = 'xyz';
let item = response.data.results.find(result => result.id === id);
console.log(item); //your desired item
});
The simple way to get (one) element from array by id:
The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.
function isBigEnough(element) {
return element >= 15;
}
var integers = [12, 5, 8, 130, 160, 44];
integers.find(isBigEnough); // 130 only one element - first
you don't need to use filter() and catch first element xx.filter()[0] like in comments above
The same for objects in array
var foo = {
"results" : [{
"id" : 1,
"name" : "Test"
}, {
"id" : 2,
"name" : "Beispiel"
}, {
"id" : 3,
"name" : "Sample"
}
]};
var secondElement = foo.results.find(function(item){
return item.id == 2;
});
var json = JSON.stringify(secondElement);
console.log(json);
Of course if you have multiple id then use filter() method to get all objects.
Cheers
function isBigEnough(element) {
return element >= 15;
}
var integers = [12, 5, 8, 130, 160, 44];
integers.find(isBigEnough); // 130 only one element - first
var foo = {
"results" : [{
"id" : 1,
"name" : "Test"
}, {
"id" : 2,
"name" : "Beispiel"
}, {
"id" : 3,
"name" : "Sample"
}
]};
var secondElement = foo.results.find(function(item){
return item.id == 2;
});
var json = JSON.stringify(secondElement);
console.log(json);
projectDetailsController.controller('ProjectDetailsCtrl', function ($scope, $routeParams, $http) {
$http.get('data/projects.json').success(function(data) {
$scope.projects = data;
console.log(data);
for(var i = 0; i < data.length; i++) {
$scope.project = data[i];
if($scope.project.name === $routeParams.projectName) {
console.log('project-details',$scope.project);
return $scope.project;
}
}
});
});
Not sure if it's really good, but this was helpful for me..
I needed to use $scope to make it work properly.
use $timeout and run a function to search in "results" array
app.controller("Search", function ($scope, $timeout) {
var foo = { "results": [
{
"id": 12,
"name": "Test"
},
{
"id": 2,
"name": "Beispiel"
},
{
"id": 3,
"name": "Sample"
}
] };
$timeout(function () {
for (var i = 0; i < foo.results.length; i++) {
if (foo.results[i].id=== 2) {
$scope.name = foo.results[i].name;
}
}
}, 10);
});
I would iterate over the results array using an angularjs filter like this:
var foundResultObject = getObjectFromResultsList(results, 1);
function getObjectFromResultsList(results, resultIdToRetrieve) {
return $filter('filter')(results, { id: resultIdToRetrieve }, true)[0];
}

Categories

Resources