How to find item from an object with Javascript? - javascript

I have my data object:
var elements = {
'element' : {
'name' : 'test',
'price' : '55'
},
'element' : {
'name' : 'letev',
'price': '223'
}
};
Now, I don't know how can I find each element by name for example.
I need to find element by name test, and then acces it's other parameters (price,..)

You must change elements to array:
var elements = [
{
'name' : 'test',
'price' : '55'
},
{
'name' : 'letev',
'price': '223'
}
];
function findElementByName(name, elementsForSearch) {
if (name) {
elementsForSearch.filter(function(elem){
return elem.name === 'name';
});
return elementsForSearch[0];
}
return {};
}
alert(findElementByName('test', elements).name)

Assuming your object was an array instead of the syntax you used:
var elements = [
{
'name' : 'test',
'price' : '55'
},{
'name' : 'letev',
'price': '223'
}
];
You can filter the element out like this:
searchName = 'test';
elements.filter(function(element){
return element.name == searchName;
});
This will only return the elements that have 'test' as name.
Or as a function:
function filterByName(array, namr){
array.filter(function(element){
return element.name == name;
});
}
Called like this:
array result = filterByName(elements, 'test');
In case you need to support IE 8 or lower, you can use a polyfill for Array.prototype.filter.

you can do that if your elements object was an array, i.e.
var elements = [{
'element' : {
'name' : 'test',
'price' : '55'
},
'element' : {
'name' : 'letev',
'price': '223'
}
}];
var price;
for (var i=0; i <elements.length; i++) {
if (elements[i].name === 'test') {
price = elements[i].price;
break;
}
}

Try with:
var elements = [
{
'name' : 'test',
'price' : '55'
},
{
'name' : 'letev',
'price': '223'
}
];
var search = 'letev';
for (var i = 0; i < elements.length; i++) {
if (elements[i].name == search) {
alert('found!');
break;
}
}
Or using Array.filter:
var search = 'letev';
var output = elements.filter(function(element) {
return element.name == search;
});

Try this
var List= (JObject)JsonConvert.DeserializeObject(jsonstring);
var result= List["element"].Children().Select(node => node["name"]== "Test").ToList();

Related

How to add <hr> after every new category

I have a array of object called elements, and the objects have two values (name and category).
[
{name : 'key1', category : 'tech'},
{name : 'key2', category : 'tech'},
{name : 'key3', category : 'tech'},
{name : 'cable1' , category : 'hard'}
{name : 'cable2' , category : 'hard'}
{name : 'cable3' , category : 'hard'}
{name : 'cable4' , category : 'hard'}
]
I want to display all names but add an <hr> whenever reaches a new category
Please help and thank you of helping.
I would first group your objects by category using Array.prototype.reduce(), then iterate over each category using Array.prototype.map():
const data = [
{name : 'key1', category : 'tech'},
{name : 'wire1' , category : 'misc'},
{name : 'key2', category : 'tech'},
{name : 'cable1' , category : 'hard'},
{name : 'key3', category : 'tech'},
{name : 'cable2' , category : 'hard'},
{name : 'wire2' , category : 'misc'}
];
const dataMap = data.reduce((acc, x) => {
acc[x.category] = [...(acc[x.category] || []), x];
return acc;
}, {});
const html = Object.entries(dataMap).map(([cat, items]) => {
return items.map(item => `<div>${item.name} ${item.category}</div>`).join('');
}).join('<hr>');
document.getElementById('app').innerHTML = html;
<div id="app"></div>
You can try something like this,
var category;
$.each(object,function(i,objval)
{
console.log(objval['name']);
if(category != "" && category != objval['category'])
{
console.log("<hr>");
}
category = objval['category'];
});
How about something like:
prev_category = undefined;
elements.forEach(function(e) {
if (i > 0 && e.category != prev_category) {
console.log('<hr>');
}
prev_category = e.category;
console.log(e.name);
});
(of course, you can replace the console.log() commands with whatever you really want to do with those texts, e.g. append them to one big string)
Iterate the object and use template literals to create the dom and check if the index of the array is not same as length then add an hr
let elements = [{
name: 'key',
category: 'tech'
},
{
name: 'cable',
category: 'hard'
}
]
let str = '';
elements.forEach(function(item, index) {
str += `<div class='elem'><span>${item.name}</span><span> ${item.category}</span></div>`
if (index !== elements.length - 1) {
str += `<hr>`
}
});
document.getElementById('container').innerHTML = str
<div id='container'></div>
If you are looking for just border then use css pseudo selector
let elements = [{
name: 'key',
category: 'tech'
},
{
name: 'cable',
category: 'hard'
}
]
let str = '';
elements.forEach(function(item, index) {
str += `<div class='elem'><span>${item.name}</span><span> ${item.category}</span></div>`
});
document.getElementById('container').innerHTML = str
.elem:not(:last-child) {
border-bottom: 1px solid black;
}
<div id='container'></div>
Basically you need to sort the data by category first then, render the element, I use react code as example
const data = [
{
name: "Huawei",
category: "phone"
},
{
name: "Iphone",
category: "phone"
},
{
name: "Refacoring Improving the design of existing code",
category: "book"
},
{
name: "Python Crash Course",
category: "book"
},
{
name: "My heart will go on",
category: "music"
},
{
name: "I'm your angel",
category: "music"
}
];
function generateCom(data) {
let listComps = [];
let category = "";
// sort the data by category
data.sort((a, b) => (a.category > b.category ? 1 : -1));
// generate the component by category
data.forEach((ele, idx) => {
if (idx === 0) {
listComps.push(<h3>{ele.category}</h3>);
listComps.push(<li>{ele.name}</li>);
category = ele.category;
return;
}
if (ele.category === category) {
listComps.push(<li>{ele.name}</li>);
} else {
listComps.push(<hr />);
listComps.push(<h3>{ele.category}</h3>);
listComps.push(<li>{ele.name} </li>);
category = ele.category;
}
});
return listComps;
}
can refer to the example
https://codesandbox.io/embed/6x0p7908qw

How to return multiple values of an array in javascript

Here I am able to return one value return fruit === 'cherries', how can I return two values , such as I tried return [fruit==='cherries', fruit==='bananas'] , How can I return two values.
var inventory = ['apples','bananas','cherries'];
function findCherries(fruit) {
return fruit === 'cherries' ;
}
console.log(inventory.find(findCherries));
You could use a logical OR -> || and Array.filter
var inventory = ['apples', 'bananas', 'cherries'];
function findCherries(fruit) {
return fruit === 'cherries' || fruit === 'bananas';
}
console.log(inventory.filter(findCherries));
You could fiter it with an array of the wanted items.
function findFruits(fruits) {
return fruit => fruits.includes(fruit);
}
var inventory = ['apples', 'bananas', 'cherries'];
console.log(inventory.filter(findFruits(['bananas', 'cherries'])));
If your inventory is below and u know which one is fruit then
function findMyInventory(type) {
var inventory = ['apples', 'bananas', 'cherries', 'beans', 'roots'];
var list = [];
if ( type == 'fruits') {
list.push(inventory.slice(0,2) );
} else if ( type == 'vegetables' ) {
list.push( inventory.slice(3,4) ) ;
}
return list;
}
if your list as below
var inventory = [
{ type: 'fruit' , name : 'apples'},
{ type: 'fruit' , name : 'bananas'},
{ type: 'fruit' , name : 'cherries'},
{ type: 'vegetable' , name : 'beans'},
{ type: 'vegetable' , name : 'roots'}
];
function findMyInventory(type) {
var myList = [];
for ( var item of inventory) {
if ( type == item.type) {
myList.push( item);
}
}
return myList;
}

Randomising array in angularjs using filter method

I have some filter options for my array like this:
$scope.sortableItems = { 'random' : 'Filter Random',
'test1' : 'Filter test1',
'test2' : 'Filter test2',
'test3' : 'Filter test3'
};
Then I set:
$scope.sortKey = 'random';
$scope.reverse = false;
And my array is created like this:
for (var i = 0; i < $scope.jsonData.length; i++) {
var item = { "test1": $scope.jsonData[i].test1, "test2": $scope.jsonData[i].test2, "test3" : $scope.jsonData[i].test3};
$scope.results.push(item);
}
Then I use:
$scope.results = $filter('orderBy')($scope.results, $scope.sortKey, $scope.reverse);
And I have a method:
$scope.random = function(){
return 0.5 - Math.random();
};
And finally I use:
ng-repeat="r in results|orderBy:sortKey:reverse"
in my html. This does not work!
However, when I set manually:
ng-repeat="r in results|orderBy:random"
then it works! Why can I not use a variable??

How see if array contains object without using JQuery

I have an array that looks like this:
var myArray = [
{'id' : 1, 'name' : 'test1'},
{'id' : 2, 'name' : 'test2'},
{'id' : 3, 'name' : 'test3'}
];
Then I have a variable that contains some id:
var someId = 2;
How can I check if myArray contains an Object, who's id is equal to someId?
You can use the .some() method:
var isThere = myArray.some(function(element) {
return element.id == someId;
});
The .some() method returns a boolean true if the callback returns true for some element. The iteration stops as soon as that happens.
If you want the element in the array and not just a yes/no answer, you can pass the same kind of callback to .find():
var theElement = myArray.find(function(element) {
return element.id == someId;
});
When that callback returns true, the iteration stops and .find() returns the element itself. If none is found, it returns undefined.
You can try following
var filteredArray = myArray.filter(function(item) {
return item.id == someId
});
if(filteredArray.length > 0) {
console.log("Found");
}
Vanilla JS:
var myArray = [
{'id' : 1, 'name' : 'test1'},
{'id' : 2, 'name' : 'test2'},
{'id' : 3, 'name' : 'test3'}
];
function findby(arr, key, val){
for(var i=0; i<arr.length; i++){
if(arr[i][key] === val){
return arr[i];
}
}
return null;
}
var found = findby(myArray, "id", 2);
alert(found.name);

looping through an array of strings only returns a letter from each string

i am trying to test the timing function in javascript by having it loop through an array of strings and displaying each after a 3 second delay but when i call the function it does a weird pattern of only taking the first letter of the first string, then the second letter of the second string, and so on... if, say the fourth item in the array has no fourth letter it prints undefined. please help.
thanks
function myFunc () {
setTimeout(function () {
var contacts = {
addressBook : [
{
'name' : 'Jane',
'email' : 'JaneDoegmail.com'
},
{
'name' : 'Meggie',
'email' : 'meggiegmail.com'
},
{
'name' : 'John',
'email' : 'johnDoegmail.com'
},
{
'name' : 'Paul',
'email' : 'paulgmail.com'
},
{
'name' : 'Bo',
'email' : 'bogmail.com'
}
]
};
var object = contacts.addressBook;
var i;
for (var i = 0; i < object.length; i++) {
var item = object[i];
var name = item.name;
var email = item.email;
document.write(name[i]);
};
if (i < 10) {
myFunc();
};
}, 3000)
}
myFunc();
Here is a working jsFiddle demo
Basically, your output is correct from what you tell it to do, it is showing you the character at the index of the name string. You should use (name) instead of (name[i]).
However, I think this is what you were probably after: suggested improvement demo
Basically, it allows the loop to be externally controller by a counter which will increment as called and stop once it has displayed all of the contact addresses.
js:
var c = document.getElementById("console");
var contacts = {
addressBook : [
{
'name' : 'Jane',
'email' : 'JaneDoegmail.com'
},
{
'name' : 'Meggie',
'email' : 'meggiegmail.com'
},
{
'name' : 'John',
'email' : 'johnDoegmail.com'
},
{
'name' : 'Paul',
'email' : 'paulgmail.com'
},
{
'name' : 'Bo',
'email' : 'bogmail.com'
}
]
};
var i = 0;
(function myFunc () {
var item = contacts.addressBook[i++];
var name = item.name;
var email = item.email;
c.innerHTML += name +", " + email + "<br>";
if (i < contacts.addressBook.length) {
setTimeout(myFunc,3000);
}
})()
Instead of document.write(name[i]);, do document.write(name);
Your document.write(name[i]);
should be
document.write(name);
Thanks
Check it out:
myFunc();
function myFunc () {
setTimeout(function () {
var contacts = {
addressBook : [
{
'name' : 'Jane',
'email' : 'JaneDoegmail.com'
},
{
'name' : 'Meggie',
'email' : 'meggiegmail.com'
},
{
'name' : 'John',
'email' : 'johnDoegmail.com'
},
{
'name' : 'Paul',
'email' : 'paulgmail.com'
},
{
'name' : 'Bo',
'email' : 'bogmail.com'
}
]
};
var object = contacts.addressBook;
var i;
for (var i = 0; i < object.length; i++) {
var item = object[i];
var name = item.name;
var email = item.email;
document.write(name+" --> ");
};
if (i < 10) {
myFunc();
};
}, 3000)}

Categories