check if record exists in javascript object - javascript

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)

Related

Object.assign() for replacing objects of a json

I have JSON looks like this:
{
"ArrayInfo": [
{
"name": "A",
"Id": "1"
},
{
"name": "B",
"Id": "2"
},
{
"name": "C",
"Id": "3"
},
{
"name": "D",
"Id": "4"
}
]
}
I want to replace an object of JSON with another object.For example I have this object :
{"name":"E","Id":"5"}
and it is going to be replaced by this object of JSON:
{"name":"B","Id":"2"}
JSON should look like this :
{
"ArrayInfo": [
{
"name": "A",
"Id": "1"
},
{
"name": "E",
"Id": "5"
},
{
"name": "C",
"Id": "3"
},
{
"name": "D",
"Id": "4"
}
]
}
What I did is to use Object.assign but the new object will be added to array instead of replacing.
(all the data is going to be dynamic but for making more understandable I use static data)
const itemToReplace = { "name": "E", "Id": "5" };
const prevItem = ArrayInfo[2]
ArrayInfo = ArrayInfo.map((el, idx) => {
return Object.assign({}, el, { prevItem: itemToReplace });
});
let NewArryInfo = ArrayInfo
console.log(NewArryInfo)
The result of console.log(NewArryInfo) :
{
"ArrayInfo": [
{
"name": "A",
"Id": "1"
},
{
"name": "B",
"Id": "2"
},
{
"name": "C",
"Id": "3"
},
{
"name": "D",
"Id": "4"
}
{
"name": "E",
"Id": "5"
}
]
}
You can use Array.prototype.splice to replace an item in Array.
const replaceItem = {"name":"E","Id":"5"}
const ArrayInfo = [
{
"name": "A",
"Id": "1"
},
{
"name": "B",
"Id": "2"
},
{
"name": "C",
"Id": "3"
},
{
"name": "D",
"Id": "4"
}
];
ArrayInfo.splice(1, 1, replaceItem); // remove second item and replace
console.log(ArrayInfo);
const object = {
"ArrayInfo": [{
"name": "A",
"Id": "1"
},
{
"name": "B",
"Id": "2"
},
{
"name": "C",
"Id": "3"
},
{
"name": "D",
"Id": "4"
}
]
};
const objectToReplace = {
"name": "B",
"Id": "2"
};
const updatedObject = Object.assign({}, object, {
ArrayInfo: object.ArrayInfo.map((info) => {
if (info.Id === objectToReplace.Id && info.name === objectToReplace.name) {
return {
"name": "E",
"Id": "5"
};
}
return info;
})
});
console.log(updatedObject);
const myArr = [
{
"name": "A",
"Id": "1"
},
{
"name": "B",
"Id": "2"
},
{
"name": "C",
"Id": "3"
},
{
"name": "D",
"Id": "4"
}
];
const replaceObj = (arr, objReplaced, objToReplaceWith) => {
const replacedObjIndex = arr.findIndex(item => JSON.stringify(item) === JSON.stringify(objReplaced));
arr[replacedObjIndex] = objToReplaceWith;
console.log(arr)
return arr;
}
replaceObj(myArr, {"name":"B","Id":"2"}, {"name":"E","Id":"5"});
In this way you can replace any object, from any position in the array.
You won't have to worry about the position of the item that you want to replace in the array and also you won't need to worry about it's keys or values.
When you map over the array you could check if each item is the one you want to replace, and if it is, return the new item instead.
ArrayInfo = ArrayInfo.map((el, idx) => {
if (el.id === prevItem.id && el.name === prevItem.name) {
return itemToReplace;
}
return el;
});
Try this!
let ArrayInfo = [{"name": "A","Id": "1"},{"name": "B","Id": "2"},{"name": "C","Id": "3"},{"name": "D","Id": "4"}];
const onReplace = {"name":"E","Id":"5"};
const toReplace = {"name": "B","Id": "2"};
function replaceArray(array, onReplace, toReplace) {
const removeIndex = array.map(item => { return item.name; }).indexOf(toReplace.name);
array.splice(removeIndex, removeIndex, onReplace);
return array
}
console.log(replaceArray(ArrayInfo, onReplace, toReplace));

display remote value in from json associative array in JavaScript

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);
}
}

Compare two JSON Arrays and rearrange new JSON Array format

Here is the my first JSON Array format...
[
{
"id": "1234",
"caption": "caption1"
},
{
"id": "2345",
"caption": "caption2"
},
{
"id": "3456",
"caption": "caption3"
}
]
and here is another JSON Array Format
[
[
{
"id": "1234",
"value": "value11"
},
{
"id": "2345",
"value": "value12"
},
{
"id": "3456",
"value": "value13"
}
],
[
{
"id": "1234",
"value": "value21"
},
{
"id": "2345",
"value": "value22"
},
{
"id": "3456",
"value": "value23"
}
]
]
The above mentioned Two JSON Arrays, i need to compare each one with Id and need to format a new JSON Array with caption and value using javascript.
[
[
{
"caption" : "caption1",
"value":"value11"
},
{
"caption" : "caption2",
"value":"value12"
},
{
"caption" : "caption3",
"value":"value13"
}
],
[
{
"caption" : "caption1",
"value":"value21"
},
{
"caption" : "caption2",
"value":"value22"
},
{
"caption" : "caption3",
"value":"value23"
}
]
]
Please help me out.
You can do it in many ways. Below I show two variants:
Option 1: Pure JavaScript
In this example the program preindex first array for faster access to it data, and then loops over second array with map() function to create new array of arrays:
// Create index version of first array
var aix = {};
for(var i=0;i<arr1.length;i++) {
aix[arr1[i].id] = arr1[i].caption;
}
// Loop over array of arrays
var res1 = arr2.map(function(arr22){
return arr22.map(function(a){
return {caption:aix[a.id], value:a.value};
}
});
Option 2: Using special SQL library (Alasql)
Here, you can JOIN to arrays automatically with special SQL statement:
var res2 = arr2.map(function(a){
return alasql('SELECT arr1.caption, a.[value] \
FROM ? a JOIN ? arr1 USING id',[a,arr1]);
});
You can try these variants in working snippet below or play with it in jsFiddle.
(Disclaimer: I am the author of Alasql)
var arr1 = [
{
"id": "1234",
"caption": "caption1"
},
{
"id": "2345",
"caption": "caption2"
},
{
"id": "3456",
"caption": "caption3"
}
];
var arr2 = [
[
{
"id": "1234",
"value": "value11"
},
{
"id": "2345",
"value": "value12"
},
{
"id": "3456",
"value": "value13"
}
],
[
{
"id": "1234",
"value": "value21"
},
{
"id": "2345",
"value": "value22"
},
{
"id": "3456",
"value": "value23"
}
]
];
// JavaScript version
var aix = {};
for(var i=0;i<arr1.length;i++) {
aix[arr1[i].id] = arr1[i].caption;
}
var res1 = arr2.map(function(arr22){
return arr22.map(function(a){
return {caption:aix[a.id], value:a.value};
});
});
document.getElementById("res1").textContent = JSON.stringify(res1);
// Alasql version
var res2 = arr2.map(function(a){
return alasql('SELECT arr1.caption, a.[value] FROM ? a JOIN ? arr1 USING id',[a,arr1]);
});
document.getElementById("res2").textContent = JSON.stringify(res2);
<script src="http://alasql.org/console/alasql.min.js"></script>
<p>Varian 1: JavaScript</p>
<div id="res1"></div>
<p>Variant 2: Alasql</p>
<div id="res2"></div>

sort and pattern match an json

Am having a json like below,
[
{
"id": "1",
"freq": "1",
"value": "Tiruchengode",
"label": "Tiruchengode"
},
{
"id": "2",
"freq": "1",
"value": "Coimbatore",
"label": "Coimbatore"
},
{
"id": "3",
"freq": "1",
"value": "Erode",
"label": "Erode"
},
{
"id": "4",
"freq": "1",
"value": "Madurai",
"label": "Madurai"
},
{
"id": "5",
"freq": "1",
"value": "Salem",
"label": "Salem"
},
{
"id": "6",
"freq": "1",
"value": "Tiruchirappalli",
"label": "Tiruchirappalli"
},
{
"id": "7",
"freq": "1",
"value": "Tirunelveli",
"label": "Tirunelveli"
}
]
I need to pattern match it with label item in this json (ie), If I type tiru, then it has to result label items having tiru substrings in it.If its a single item array I know how to pattern match and sort it. Here am completely unaware that, how to pattern match using label item in the array. Is it possible to?. I need to do with Pure javascript, any help guys?
You can use the functional array methods introduced in JavaScript 1.6, specifically filter:
var search = 'tiru';
var results = obj.filter(function(item) {
var a = item.label.toUpperCase();
var b = search.toUpperCase();
return a.indexOf(b) >= 0;
});
If you wanted labels only, you can then use map to return only that property alone:
var labels = obj.filter(function(item) {
var a = item.label.toUpperCase();
var b = search.toUpperCase();
return a.indexOf(b) >= 0;
}).map(function(item) {
return item.label;
});
Essentially, filter is a method available to any Array which returns a new Array containing only those members for which the supplied function return true.
JSON.parse() will help convert the jsonString to JsonObject then just iterate the object use indexOf for pattern matching.
var jsonString = '[{"id": "1","freq": "1","value": "Tiruchengode","label": "Tiruchengode"},{"id": "2","freq": "1","value": "Coimbatore","label": "Coimbatore"},{"id": "3","freq": "1","value": "Erode","label": "Erode"},{"id": "4","freq": "1","value": "Madurai","label": "Madurai"},{"id": "5","freq": "1","value": "Salem","label": "Salem"},{"id": "6","freq": "1","value": "Tiruchirappalli","label": "Tiruchirappalli"},{"id": "7","freq": "1","value": "Tirunelveli","label": "Tirunelveli"}]';
var jsonObjects = JSON.parse(jsonString);
var pattern = "tiru";
for(var key in jsonObjects){
var label = jsonObjects[key].label.toUpperCase();
if(label.indexOf(pattern.toUpperCase()) != -1){
document.write(label+"<br/>");
}
}

How to select json item from the array

From the below JSON, how can I retrieve title from the note and notes using a for loop and ajax to retrieve?
{
"infos": {
"info": [
{
"startYear": "1900",
"endYear": "1930",
"timeZoneDesc": "daweerrewereopreproewropewredfkfdufssfsfsfsfrerewrBlahhhhh..",
"timeZoneID": "1",
"note": {
"notes": [
{
"id": "1",
"title": "Mmm"
},
{
"id": "2",
"title": "Wmm"
},
{
"id": "3",
"title": "Smm"
}
]
},
"links": [
{ "id": "1", "title": "Red House", "url": "http://infopedia.nl.sg/articles/SIP_611_2004-12-24.html" },
{ "id": "2", "title": "Joo Chiat", "url": "http://www.the-inncrowd.com/joochiat.htm" },
{ "id": "3", "title": "Bake", "url": "https://thelongnwindingroad.wordpress.com/tag/red-house-bakery" }
]
}
I tried out the code below but it doesn't work - it either says:
is null
not an object
length is null
r not an object
var detail = eval(xmlhttprequest.responseText)
var rss = detail.infos.info
for(var i = 0; i<rss.length; i++)
startyear += rss[i].startyear
Use
for (i = 0; i < 3; i++) {
alert(JSON.infos.info[0].note.notes[i].title);
}
TRY IT HERE: JSFIDDLE WORKING EXAMPLE
BTW your JSON is not valid. Use this JSON:
var JSON = {
"infos": {
"info": [
{
"startYear": "1900",
"endYear": "1930",
"timeZoneDesc": "daweerrewereopreproewropewredfkfdufssfsfsfsfrerewrBlahhhhh..",
"timeZoneID": "1",
"note": {
"notes": [
{
"id": "1",
"title": "Mmm"
},
{
"id": "2",
"title": "Wmm"
},
{
"id": "3",
"title": "Smm"
}
]
},
"links": [
{
"id": "1",
"title": "Red House",
"url": "http://infopedia.nl.sg/articles/SIP_611_2004-12-24.html"
},
{
"id": "2",
"title": "Joo Chiat",
"url": "http://www.the-inncrowd.com/joochiat.htm"
},
{
"id": "3",
"title": "Bake",
"url": "https://thelongnwindingroad.wordpress.com/tag/red-house-bakery"
}
]
}
]
}
}
EDIT:
Here is what you want:
var infoLength= JSON.infos.info.length;
for (infoIndex = 0; infoIndex < infoLength; infoIndex++) {
var notesLength= JSON.infos.info[infoIndex].note.notes.length;
for (noteIndex = 0; noteIndex < notesLength; noteIndex++) {
alert(JSON.infos.info[infoIndex].note.notes[noteIndex].title);
}
}
Putting your json into an var called obj, use the following:
obj.infos.info[0].note.notes[0].title
http://jsfiddle.net/Znq34/
Well the "path" to the JSON notes array-like object is:
json.infos.info[0].note.notes;
So you could do something like:
var notes = json.infos.info[0].note.notes;
var titles = [];
for (var i = 0, len = notes.length; i < len; i++)
{
titles.push(notes[i].title);
}
alert('titles is: ' + titles.join(', '));
Fiddle: http://jsfiddle.net/garreh/uDxqD/
Are you using jQuery? ;-)
// Assuming your using "success" in ajax response
success: function(json)
{
var titles = $(json.infos.info[0].note.notes).map(function() {
return this.title;
}).get();
alert(titles.join(', '));
}
First count the length of notes
var len = jsonobject.infos.info.note.notes.length;
Then loops through and get
var title = jsonobject.infos.info.note.notes[i].title;

Categories