How can I display the members.Rating for "Jones, Jim"? I have tried the syntax: echo members[$temp].Rating but it doesn't work.
let $temp = "Jones, Jim";
var members = [
{ "Rating": "1500", "Name": "Williams, Bill"},
{ "Rating": "2000", "Name": "Smith, Paul" },
{ "Rating": "1000", "Name": "Jones, Jim" },
{ "Rating": "1750", "Name": "Reynolds, Beverly" } ]
Use Array.find:
let $temp = "Jones, Jim";
var members = [
{ "Rating": "1500", "Name": "Williams, Bill"},
{ "Rating": "2000", "Name": "Smith, Paul" },
{ "Rating": "1000", "Name": "Jones, Jim" },
{ "Rating": "1750", "Name": "Reynolds, Beverly" } ]
console.log(
members.find(x => x.Name === $temp).Rating
)
You can't directly reference a member of an array by value, only by index.
So, you'll have to use the find method, like so:
const tempMember = members.find(p => p.Name === $temp)
const tempMemberRating= tempMember && tempMember.Rating
Note that if find doesn't find the element you want, it will return undefined. This makes the mult-line approach necessary, as simply calling it all in one line could result in a TypeError. e.g.:
members.find(p => p.Name === "Johnson, Jimmy").Rating
Since find returns undefined here, you're attempting to reference undefined.Rating, which will throw an error.
Try this:
For (var i=0 ;i <members.length ;i++){
If ( members[i].Name == $temp ){
console.log (members[i].Raiting);
}
}
Related
How can I concatenate this json to obtain it:
complements = ["XYZ 3, CDE TR, AAA 5", "", "NDP 3, DDD FR"] ?
Each address can contain a set of complements which must be concatenated and separated by a comma.
P.s: I'm using javascript.
P.s2: Complements can be null like in the second group in JSON.
[
{
"postalcode": "1234",
"street": "ABC",
"number": "1",
"complement": [
{
"type": "B",
"name": "XYZ",
"description": "3"
},
{
"type": "C",
"name": "CDE",
"description": "TR"
},
{
"type": "D",
"name": "AAA",
"description": "5"
}
]
},
{
"postalcode": "444",
"street": "No complements",
"number": "5"
},
{
"postalcode": "2222",
"street": "BBB",
"number": "2",
"complement": [
{
"type": "E",
"name": "NDP",
"description": "3"
},
{
"type": "F",
"name": "DDD",
"description": "FR"
}
]
}
];
My code I'm getting this.complementsList.forEach is not a function.
getComplement(addressesResponse){
this.complementsList = JSON.parse(addressesResponse);
this.complementsList.forEach((item) => {
Object.defineProperty(item, 'complements', {
get: function() {
return this.complement.map((c) => `${c.name} ${c.description}`).join(', '); }
})
});
Source: https://salesforce.stackexchange.com/questions/367713/how-to-render-a-json-in-the-same-line-lwc
how i solved it :
arr.map((x)=>x.complement != null? (x.complement.map((y)=>y.name+' '+y.description)+"") :'');
Having a javascript object, you can go through the keys of the object and combine some of them into strings
It will look something like this:
const jsonObject = [{...}, {...}, ...]
const complements = [];
jsonObject.forEach((item) => {
let complement = item['complement'].reduce((result, currObj)
=> result += (currObj.name+' '+currObj.description), "");
complements.push(complement);
});
This is just an example. There are many ways to do it.
I have a web app which passes delimited fields to another web page. It works fine! But... I want to list the fields (Name) that don't exist in the javascript object. How can this be accomplished?
JS object:
var members = [ { "Class": "E", "Rating": "1000", "ID": "16720664", "Name": "Adeyemon, Murie", "Expires": "1000.10.10" },
{ "Class": "B", "Rating": "1735", "ID": "12537964", "Name": "Ahmed, Jamshed", "Expires": "2018.10.18" },
{ "Class": "C", "Rating": "1535", "ID": "12210580", "Name": "Attaya, James", "Expires": "2019.01.12" },
{ "Class": "F", "Rating": "0001", "ID": "16281977", "Name": "Auld, Thomas", "Expires": "1000.10.10" },
{ "Class": "B", "Rating": "1793", "ID": "10117780", "Name": "Badamo, Anthony", "Expires": "2018.09.12" }
]
JS CODE:
let dataString = "Adeyemon, Murie|Ahmed, Jamshed|Attaya, James|Badamo, Anthony|Birmingham, Gerald|";
let splitString = dataString.split("|");
for (let i = 0; i < splitString.length; i++) {
$temp = splitString[i - 1];
if ($temp > "") {
members.find(x => x.Name === $temp);
}
}
use filter
var dataString =
'Adeyemon, Murie|Ahmed, Jamshed|Attaya, James|Badamo, Anthony|Birmingham, Gerald|'
var members = [{"Class":"E","Rating":"1000","ID":"16720664","Name":"Adeyemon, Murie","Expires":"1000.10.10"},{"Class":"B","Rating":"1735","ID":"12537964","Name":"Ahmed, Jamshed","Expires":"2018.10.18"},{"Class":"C","Rating":"1535","ID":"12210580","Name":"Attaya, James","Expires":"2019.01.12"},{"Class":"F","Rating":"0001","ID":"16281977","Name":"Auld, Thomas","Expires":"1000.10.10"},{"Class":"B","Rating":"1793","ID":"10117780","Name":"Badamo, Anthony","Expires":"2018.09.12"}]
var res = dataString.split('|').filter(
name => !members.map(o => o.Name).find(n => n === name)
).filter(name=>name.trim()!=='')
console.log(res);
You can first create Name to object mapping and then search name from string in this object/map which will cost O(n) for n names.
var members = [ { "Class": "E", "Rating": "1000", "ID": "16720664", "Name": "Adeyemon, Murie", "Expires": "1000.10.10" },
{ "Class": "B", "Rating": "1735", "ID": "12537964", "Name": "Ahmed, Jamshed", "Expires": "2018.10.18" },
{ "Class": "C", "Rating": "1535", "ID": "12210580", "Name": "Attaya, James", "Expires": "2019.01.12" },
{ "Class": "F", "Rating": "0001", "ID": "16281977", "Name": "Auld, Thomas", "Expires": "1000.10.10" },
{ "Class": "B", "Rating": "1793", "ID": "10117780", "Name": "Badamo, Anthony", "Expires": "2018.09.12" }
];
var nameMap = members.reduce((prev, next) => {
prev[next.Name] = next;
return prev;
}, {});
let dataString = "Adeyemon, Murie|Ahmed, Jamshed|Attaya, James|Badamo, Anthony|Birmingham, Gerald|";
let names = dataString.split("|");
let result = names.filter(name => name && !(name in nameMap));
console.log(result);
Try reducing the members array to a Set of names. Then you can filter your splitString array using Set.prototype.has()
const members = [{"Class":"E","Rating":"1000","ID":"16720664","Name":"Adeyemon, Murie","Expires":"1000.10.10"},{"Class":"B","Rating":"1735","ID":"12537964","Name":"Ahmed, Jamshed","Expires":"2018.10.18"},{"Class":"C","Rating":"1535","ID":"12210580","Name":"Attaya, James","Expires":"2019.01.12"},{"Class":"F","Rating":"0001","ID":"16281977","Name":"Auld, Thomas","Expires":"1000.10.10"},{"Class":"B","Rating":"1793","ID":"10117780","Name":"Badamo, Anthony","Expires":"2018.09.12"}]
const dataString = "Adeyemon, Murie|Ahmed, Jamshed|Attaya, James|Badamo, Anthony|Birmingham, Gerald|";
const names = members.reduce((c, {Name}) => c.add(Name), new Set())
const missing = dataString.split('|')
.filter(name => name.trim() && !names.has(name))
.join('; ') // output from your comment on another answer
console.info(missing)
I've added in the name.trim() to filter out the empty record created by the trailing | in your dataString.
The reason for creating a Set is to avoid searching the entire members array for each name in dataString. Set.prototype.has() should be O(1)
I have a dictionary that looks a little like this:
var index = {
"Italian": [
{
"name": "Il Brigante",
"rating": "5.0"
},
{
"name": "Giardino Doro Ristorante",
"rating": "5.0"
}
],
"Mexican": [
{
"name": "Cosme",
"rating": "5.0"
}
]
}
I also have a search bar that people can enter queries into. What I want to do is take the query and search for it inside index.
Example: search = "italian", results = {"name": "Il Brigante", "rating": "5.0"}, {"name": "Giardino Doro Ristorante", "rating": "5.0"}
Is that kind of search possible? Any help would be appreciated. Thanks so much in advance. Happy 4th!
Cheers,
Theoi
You can try following
var index = {
"Italian": [{
"name": "Il Brigante",
"rating": "5.0"
},
{
"name": "Giardino Doro Ristorante",
"rating": "5.0"
}
],
"Mexican": [{
"name": "Cosme",
"rating": "5.0"
}]
};
var search = "italian";
var results = Object.keys(index).reduce(function(a, b) {
if (b.toLowerCase() === search.toLowerCase()) {
return a.concat(index[b]);
}
return a;
}, []);
console.log(results);
May Be a Requirement Later!
In case you want to for the partial match, you just need to replace
if (b.toLowerCase() === search.toLowerCase()) {
with
if(b.toLowerCase().indexOf(search.toLowerCase()) !== -1) {
For tweaking - plunker
You can use hasOwnProperty directly, but that will only return exact matches. Simplest way is to loop through the index properties and look for a match and return the resulting value.
var index = {
"Italian": [
{
"name": "Il Brigante",
"rating": "5.0"
},
{
"name": "Giardino Doro Ristorante",
"rating": "5.0"
}
],
"Mexican": [
{
"name": "Cosme",
"rating": "5.0"
}
]
}
console.log(index.hasOwnProperty('italian'));
console.log(index.hasOwnProperty('Italian'));
console.log(dictionarySearch('Italian', index));
function dictionarySearch(term, dictionary)
{
var found = false;
if (typeof dictionary === 'object') {
for(property in dictionary) {
if (dictionary.hasOwnProperty(property)) {
if (property.toLowerCase() === term.toLowerCase()) {
found = dictionary[property];
}
}
}
}
return found;
}
Check out square-bracket-notation.
This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime).
Source with examples
Applying this to your problem:
var index = {
"Italian": [
{
"name": "Il Brigante",
"rating": "5.0"
},
{
"name": "Giardino Doro Ristorante",
"rating": "5.0"
}
],
"Mexican": [
{
"name": "Cosme",
"rating": "5.0"
}
]
}
var query = "Italian"
var result = index[query]
console.log(index["Italian"])
I assume that there is no situation when we have indexes like 'itAlIaN'/ 'italian' / 'ITALIAN' so index is unique no matter if you have lower/upper case
var index = {
"Italian": [
{
"name": "Il Brigante",
"rating": "5.0"
},
{
"name": "Giardino Doro Ristorante",
"rating": "5.0"
}
],
"Mexican": [
{
"name": "Cosme",
"rating": "5.0"
}
]
}
// function to normalize index by having keys lowercase
function lowercaseIndex (obj) {
var keys = Object.keys(obj);
var n = keys.length;
var normalized = {};
while (n--) {
var key = keys[n];
normalized[key.toLowerCase()] = obj[key];
}
return normalized;
}
index = lowercaseIndex(index);
function search(needle) {
return index[needle.toLowerCase()] || "No results";
}
// tests
console.log(search('Italian')); // output: [{"name":"Il Brigante","rating":"5.0"},{"name":"Giardino Doro Ristorante","rating":"5.0"}]
console.log(search('italian')); // output: [{"name":"Il Brigante","rating":"5.0"},{"name":"Giardino Doro Ristorante","rating":"5.0"}]
console.log(search('iTaLiAn')); // output: [{"name":"Il Brigante","rating":"5.0"},{"name":"Giardino Doro Ristorante","rating":"5.0"}]
console.log(search('mexican')); // output: [{"name":"Cosme","rating":"5.0"}]
console.log(search('English')); // output: "No results"
var brands = [];
brands = [null, {
"id": "1",
"image": "/images/brands/surf_excel.png",
"name": "Surf Excel",
"productCount": "6"
}, {
"id": "2",
"image": "/images/brands/rin.png",
"name": "Rin",
"productCount": "5"
}, {
"id": "3",
"image": "/images/brands/ariel.png",
"name": "Ariel",
"productCount": "4"
}];
Now i want to get the name where id = 3. I tried
var data = _.filter(brands, { 'id': 3 });
console.log(data.name);
But its giving error can't read property of undefined. Assuing there will be only one record for id =3, Can anyne help me on this. How to get name from given id in the above structure.
If there is any better way to get the same result that is also appreciated.
As you have specified lodash and using it's _.filter() method. You can use pass predicate which can a function which will be invoke per iteration. As note it will return you an array.
var data = _.filter(brands, function(brand){
return brand != null && brand.id == 3;
});
console.log(data[0].name);
if you want only one element the use _.find()
var data = _.find(brands, function(brand){
return brand != null && brand.id == 3;
});
console.log(data.name);
Use native JavaScript Array#find method.
var brands = [];
brands = [null, {
"id": "1",
"image": "/images/brands/surf_excel.png",
"name": "Surf Excel",
"productCount": "6"
}, {
"id": "2",
"image": "/images/brands/rin.png",
"name": "Rin",
"productCount": "5"
}, {
"id": "3",
"image": "/images/brands/ariel.png",
"name": "Ariel",
"productCount": "4"
}];
var data = brands.find(function(v) {
return v && v.id == "3";
});
console.log(data.name);
Check polyfill option for find method for older browser.
If you want to filter out the array then use Array#filter method.
var brands = [];
brands = [null, {
"id": "1",
"image": "/images/brands/surf_excel.png",
"name": "Surf Excel",
"productCount": "6"
}, {
"id": "2",
"image": "/images/brands/rin.png",
"name": "Rin",
"productCount": "5"
}, {
"id": "3",
"image": "/images/brands/ariel.png",
"name": "Ariel",
"productCount": "4"
}];
var data = brands.filter(function(v) {
return v && v.id == "3";
});
console.log(data[0].name);
UPDATE :
You are provided an object as the second argument as per documentation which uses _.matches for property value comparison. In your array id property holds a string value but you were provided as a number in the filter just change it to string will make it work or use callback function as in #Satpal answer.
var brands = [];
brands = [null, {
"id": "1",
"image": "/images/brands/surf_excel.png",
"name": "Surf Excel",
"productCount": "6"
}, {
"id": "2",
"image": "/images/brands/rin.png",
"name": "Rin",
"productCount": "5"
}, {
"id": "3",
"image": "/images/brands/ariel.png",
"name": "Ariel",
"productCount": "4"
}];
var data = _.filter(brands, {
'id': "3"
});
console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.js"></script>
Aside from using filter() instead of find(), you're actually pretty close. The reason you're not seeing any results is because the object predicates that you can pass to find()/filter() perform strict equality comparisons. Meaning, 3 === '3' will evaluate to false.
I have following array:
var array = [
{
"milestoneTemplate": {
"id": "1",
"name": "TEST1"
},
"id": "1",
"date": "1416680824",
"type": "ETA",
"note": "Note",
"color": "66FF33"
},
{
"milestoneTemplate": {
"id": "2",
"name": "Test 2"
},
"id": "2",
"date": "1416680824",
"type": "ATA",
"note": "Note 22",
"color": "66FF00"
}
];
And now i would like to check in forEach loop that object (which is passed in param of the function) is existing in array by his ID.
In case that not = do push into existing array.
arrayOfResults.forEach(function(entry) {
if(entry != existingInArrayByHisId) {
array.push(entry);
}
});
Thanks for any advice
You could create a helper function thats checks if an array contains an item with a matching property value, something like this:
function checkForMatch(array, propertyToMatch, valueToMatch){
for(var i = 0; i < array.length; i++){
if(array[i][propertyToMatch] == valueToMatch)
return true;
}
return false;
}
which you can then use like so:
arrayOfResults.forEach(function (entry) {
if (!checkForMatch(array, "id", entry.id)) {
array.push(entry);
}
});