javascript + combine json arrays based on key, - javascript

I am trying to merger two json to one json. I don't want merge all keys, I added my code.
Code should be in javascript or node (underscore).
var json1 = [{user_id:1,friend_id:2,desc:'aaa'}, {user_id:3,friend_id:4,desc:'ccc'}, {user_id:1,friend_id:1,desc:'ccc'} , {user_id:1,friend_id:3,desc:'ccc'} ];
var json2 = [{reference_id:1,name:'A'},{reference_id:2,name:'B'},{reference_id:3,name:'C',age:30},{reference_id:4,name:'D'}];
Expecting Output:
output:
json1 = [{user_id:1,friend_id:2,desc:'aaa',user_name:'A',friend_name:'B'}, {user_id:3,friend_id:4,desc:'ccc',user_name:'C',friend_name:'D'}, {user_id:1,friend_id:1,desc:'ccc',user_name:'A',friend_name:'A'} , {user_id:1,friend_id:3,desc:'ccc',user_name:'A',friend_name:'C'} ];
Logic Js Code:
for (var i = 0; i < json1.length; i++) {
var user_id = json1[i].user_id;
var friend_id = json1[i].friend_id;
for (var j = 0; j < json2.length; j++) {
if (json2[j].reference_id == user_id) {
json1[i].user_name = json2[j].name;
}
if (json2[j].reference_id == friend_id) {
json1[i].friend_name = json2[j].name;
}
}
}
I attached my code in jsfiddle.Click Here
The same code should be convert into underscore.

You are repeating some effort here. Doesn't really matter if json2.length is small; but if it is large you will pay a penalty: you are looping over every element of json2 for every time you look at an element of json1. So instead, think of it this way:
var personMap = {};
json2.forEach(function(item) {
personMap[item.reference_id] = item.name;
});
json1.forEach(function(item) {
item.user_name = personMap[item.user_id];
item.friend_name = personMap[item.friend_id];
});

Your code in plain vanilla JS should work, except for "==" in the places where you've mistakenly put "=".
Replace these:
if (json2[j].reference_id = user_id) {
...
if (json2[j].reference_id = friend_id) {
...
with these:
if (json2[j].reference_id == user_id) {
...
if (json2[j].reference_id == friend_id) {
Try this is underscore:
_.map(json1, function(item){
var user_id = item.user_id;
var friend_id = item.friend_id;
_.map(json2, function(item2){
if (item2.reference_id == user_id) {
item.user_name = item2.name;
}
if (item2.reference_id == friend_id) {
item.friend_name = item2.name;
}
});
});

Related

Problems with Arrays on Angular 5

I have this problem:
I have a search in the component "Table" (PrimeNg).
This search is to start when I post a character in the input. The search is correct, but when I clean the entry, the values do not return. This line at the beginning is just for this "this.groupExamples = this.Examples group;" but apparently when I change the elements of an array the other is affected.
public getGrupoExames(){
this.serviceExames.getGrupoExames()
.subscribe((response)=> {
this.grupoExames = response;
this.grupoExamesAux = response;
}, (erro)=> {
console.log("Erro");
});
}
private filtarGrupoExames(event){
let filtro: GrupoExame[] = [];
this.grupoExames = this.grupoExamesAux.slice();
for(let i = 0; i < this.grupoExames.length; i++) {
let grupo = this.grupoExames[i];
let listaExames = [];
for(let j = 0; j < grupo.exames.length; j++){
let exame = grupo.exames[j];
if(exame.nome.toLowerCase().indexOf(event.toLowerCase()) == 0) {
listaExames.push(exame);
}
}
grupo.exames = listaExames;
filtro.push(grupo);
}
this.grupoExames = filtro;
}
I suppose that you display whatever is inside your grupoExames, if that is correct you can try this structure
if(event.target.value.length > 1) {
do the filter
}
else {
this.getGrupoExames();
}
Maybe another more ambiguous solution is to create a button to delete the filter and access to all the content .
Hope it helps you!

Javascript module pattern with array

I have an exercise which i don´t really understand, so I hope for some help for this.
I should hardcode a simple array and the exercise tells me this:
Often, when we create our web applications, we have the need for test data. Implement a reusable nodejs module, using JavaScripts module pattern, which can provide random test data as sketched below:
var data = dataGenerator.getData(100,"fname, lname, street, city, zip");
This should return a JavaScript array (not JSON) with 100 test data on the form:
[{fname: "Bo", lname:"Hansen", street: "Lyngbyvej 26", city: "Lyngby", zip: "2800"},..]
If you call it like this:
var data = dataGenerator.getData(25,fname, lname);
it should return 25 test data as sketched below:
[{fname: "Bo", lname:"Hansen"},..]
I have some code here, but this dosen´t work yet:
var dataGenerator = (function () {
var data = [
{
fname : "Bo",
lname : "Bosen",
...
},
{
fname : "jashkjh",
lname : "jhsdkfj",
...
},
...
];
return {getData : function (count, fields) {
var result = [];
var i = 0;
var field;
var j;
fields = fields.split(/\s*,\s*/);
while (i < count && i < data.length) {
result.push({});
// Det objekt vi arbejder på lige nu er i result[i]
for (j = 0; j < fields.length; j++) {
result[i][fields[j]] = data[i][fields[j]];
}
i++;
}
return result;
}};
})();
module.exports = dataGenerator;
I do not know the data body, but could try:
var data=[{fname:"Bo",lname:"Bosen",street:"Lyngbyvej 26",city:"Lyngby",zip:"2800"},{fname:"jashkjh",lname:"jhsdkfj",street:"Fmsn 9",city:"Pra",zip:"1600"},{fname:"eeee",lname:"aaaa",street:"Eda 5",city:"Pre",zip:"3500"}];
var dataGenerator = {
getData: function(count, fieldsStr){
var result = [], fields = fieldsStr.split(/\s*,\s*/), i = 0;
while(i < count && data[i]){
var item = {};
fields.forEach(function(key){
item[key] = data[i][key]
});
result.push(item);
i++
}
return result
}
}
var results = dataGenerator.getData(2,"fname, zip");
document.write(JSON.stringify(results))

Get anchor tag values in jQuery

I have a html tag like this.
<a class="employee_details" target="_blank" href="index1.php?name=user1&id=123">User</a>
I need to get the two parameter values in jquery
<script type="text/javascript">
$(function () {
$('.employee_details').click(function () {
var status_id = $(this).attr('href').split('name');
alert(status_id[0]);
});
});
</script>
Any help in getting both the parameter values in two variables in javascript.
I want to get user1 and 123 in two variables using jQuery
Thanks
Kimz
You can use URLSearchParams as a most up-to-date and modern solution:
let href = $(this).attr('href');
let pars = new URLSearchParams(href.split("?")[1]);
console.log(pars.get('name'));
Supported in all modern browsers and no jQuery needed!
Original answer:
Try this logic:
var href = $(this).attr('href');
var result = {};
var pars = href.split("?")[1].split("&");
for (var i = 0; i < pars.length; i++)
{
var tmp = pars[i].split("=");
result[tmp[0]] = tmp[1];
}
console.log(result);
So you'll get the parameters as properties on result object, like:
var name = result.name;
var id = result.id;
Fiddle.
An implemented version:
var getParams = function(href)
{
var result = {};
var pars = href.split("?")[1].split("&");
for (var i = 0; i < pars.length; i++)
{
var tmp = pars[i].split("=");
result[tmp[0]] = tmp[1];
}
return result;
};
$('.employee_details').on('click', function (e) {
var params = getParams($(this).attr("href"));
console.log(params);
e.preventDefault();
return false;
});
Fiddle.
$(function() {
$('.employee_details').on("click",function(e) {
e.preventDefault(); // prevents default action
var status_id = $(this).attr('href');
var reg = /name=(\w+).id=(\w+)/g;
console.log(reg.exec(status_id)); // returns ["name=user1&id=123", "user1", "123"]
});
});
// [0] returns `name=user1&id=123`
// [1] returns `user1`
// [2] returns `123`
JSFiddle
NOTE: Better to use ON method instead of click
Not the most cross browser solution, but probably one of the shortest:
$('.employee_details').click(function() {
var params = this.href.split('?').pop().split(/\?|&/).reduce(function(prev, curr) {
var p = curr.split('=');
prev[p[0]] = p[1];
return prev;
}, {});
console.log(params);
});
Output:
Object {name: "user1", id: "123"}
If you need IE7-8 support this solution will not work, as there is not Array.reduce.
$(function () {
$('.employee_details').click(function () {
var query = $(this).attr('href').split('?')[1];
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
var varName = decodeURIComponent(pair[0]);
var varValue = decodeURIComponent(pair[1]);
if (varName == "name") {
alert("name = " + varValue);
} else if (varName == "id") {
alert("id = " + varValue);
}
}
});
});
It's not very elegant, but here it is!
var results = new Array();
var ref_array = $(".employee_details").attr("href").split('?');
if(ref_array && ref_array.length > 1) {
var query_array = ref_array[1].split('&');
if(query_array && query_array.length > 0) {
for(var i = 0;i < query_array.length; i++) {
results.push(query_array[i].split('=')[1]);
}
}
}
In results has the values. This should work for other kinds of url querys.
It's so simple
// function to parse url string
function getParam(url) {
var vars = [],hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
// your code
$(function () {
$('.employee_details').click(function (e) {
e.preventDefault();
var qs = getParam($(this).attr('href'));
alert(qs["name"]);// user1
var status_id = $(this).attr('href').split('name');
});
});

Javascript | Objects, Arrays and functions

may be you can help me. How can I create global object and function that return object values by id?
Example:
var chat = {
data : {
friends: {}
}
}
....
/*
JSON DATA RETURNED:
{"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
*/
onSuccess: function(f){
chat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends.push(f.users[i])
}
}
How can I create a new function (It will return values by friend_id)?
get_data_by_id: function (what, friend_id) {
/*obj.what = getfrom_globalobject(chat.data.friends???)*/
}
Example of use:
var friend_name = get_data_by_id(name, 62);
var friend_username = get_data_by_id(username, 62);
var friend_avatar = get_data_by_id(thumb, 62);
Try:
get_data_by_id: function (what, friend_id) {
return chat.data.friends[friend_id][what];
}
... but use it like:
var friend_name = get_data_by_id('name', 62);
...and set up the mapping with:
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i];
}
You cannot .push() to an object. Objects are key => value mappings, so you need to use char.data.friends[somekey] = f.users[i];
If you really just want a list with numeric keys, make x5fastchat.data.friends an array: x5fastchat.data.friends = [];
However, since you want to be able to access the elements by friend_id, do the following:
onSuccess: function(f){
x5fastchat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i]
}
}
get_data_by_id: function (what, friend_id) {
obj[what] = chat.data.friends[friend_id][what];
}
Note the obj[what] instead of your original obj.what: When writing obj.what, what is handled like a string, so it's equal to obj['what'] - but since it's a function argument you want obj[what].
Take a look at the following code. You can simply copy paste it into an HTML file and open it. click "go" and you should see the result. let me know if I did not understand you correctly. :
<script>
myObj = { "field1" : { "key1a" : "value1a" }, "field2" : "value2" }
function go()
{
findField(myObj, ["field2"])
findField(myObj, ["field1","key1a"])
}
function findField( obj, fields)
{
var myVal = obj;
for ( var i in fields )
{
myVal = myVal[fields[i]]
}
alert("your value is [" + myVal + "]");
}
</script>
<button onclick="go()">Go</button>
I would recommend using the friend objects rather than getting them by id and name.
DATA = {"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
// simple data store definition
Store = {items:{}};
NewStore = function(items){
var store = Object.create(Store);
store.items = items || {};
return store
};
Store.put = function(id, item){this.items[id] = item;};
Store.get = function(id){ return this.items[id]; };
Store.remove = function(id){ delete this.items[id]; };
Store.clear = function(){ this.items = {}; };
// example
var chat = {
data : {
friends : NewStore()
}
}
// after data loaded
chat.data.friends.clear();
for( var i = 0; i < DATA.users.length; i += 1 ){
var user = DATA.users[i];
chat.data.friends.put( user.friend_id, user );
}
getFriend = function(id){ return chat.data.friends.get( id ); }
var friend = getFriend(66);
console.log(friend.name);
console.log(friend.username);
console.log(friend.thumb);

Using separators in JS

I'm currently writing a program that uses ";" as a seperator and extracts the url up until that point upon searching the content.
So it has the format:
name;surname
In searching the given arrays... I decided to go the extra mile and test for arrays without the ";" but this has confused the program - it has no idea of the ";" position anymore and this throws a spanner in the works!
Here is my code so far - many thanks in advance!
pages =
[
"The first", "An;alternative;page", "Yet another page"
]
u_c_pages =
[
"www.cam.ac.uk;"+pages[0]
,
"www.warwick.ac.uk"+pages[1]
,
"www.kcl.ac.uk;"+pages[1]
,
"www;"+pages[2]
]
var pattern5 = prompt('5) Please enter a search term:');
function url1_m1(u_c_pages,pattern)
{
var seperator = [];
var seperatorPos = [];
if(pattern)
{
for (var i = 0; i < u_c_pages.length; i++)
{
var found = true;
if((u_c_pages[i].indexOf(";"))<0)
{
found=false;
}
else
{
seperator[seperator.length] = i;
seperatorPos[seperatorPos.length] = (u_c_pages[i].indexOf("|"));
}
}
if(seperator.length==0)
{
return("Nothing found!");
}
else
var found2 = "";
{
for (var j = 0; j < seperator.length; j++)
{
if(u_c_pages[j].substring(seperatorPos[j],u_c_pages[j].length-1).toLowerCase().indexOf(pattern.toLowerCase()) >= 0)
{
found2 = (u_c_pages[j].substring(0,seperatorPos[j]));
break;
}
}
return(found2)
}
}
else
{
// only returned when the user decides to type in nothing
return("Nothing entered!");
}
}
alert(url1_m1(u_c_pages,pattern5));
enjoy the power of regex:
on JSFiddle
pages = ["The first", "An;alternative;page", "Yet another page"];
u_c_pages = [
"www.lboro.ac.uk;"+pages[0],
"www.xyz.ac.uk;"+pages[1],
"www.xyz.ac.uk;"+pages[1],
"www;"+pages[2]
];
var pattern5 = prompt('5) Please enter a search term:');
function url1_m1(u_c_pages,pattern)
{
// escape search pattern
pattern = pattern.toLowerCase().replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
pattern = new RegExp('^([^;]+);.*?' + pattern, 'i');
var result = null;
for(var i=0;i<u_c_pages.length;i++) {
if((result = u_c_pages[i].match(pattern))) {
return result[1];
}
}
return false;
}
alert(url1_m1(u_c_pages,pattern5));
You can use String.split(";") to split a string into segments. The parameter is the seperator.

Categories