Angular 2 – how to update model

I receive data model using a service:

  return this.http.get(queryUrl, opts)   .map((response: Response) => {
    return (<any>response.json()).data.map(el => {
      return new User({
        id: item.id,
        name : item.name
      });
    })   

This gets accesed from component

      makeRequest() {
          this.result = this.myService.loadData()
      }

And passed down as result: Observable<User[]>; to a form, this on Submit sends a post request which gets saved to the backend,all this works. The problem is that my model/website doesn’t get updated this way.

Probably it’s a silly question but, how do I update my model (now after saving to backend the app still holds the old data)? What ar the strategies? Do I have to pass updated data object back to top component and then update?


Source: stackoverflow-javascript

[PHP]Same Array into different Bracket

In PHP, I have an array which I created and usueally the value of that array are like [‘a’,’b’,’c’], but I dont know why, my array is in this form : [[‘a’],[‘b’],[‘c’]]
Here is my code :

<?php 
$res1 = array();
$result1 = mysqli_query($con,$dfcv) ;
 while($row2 = mysqli_fetch_array($result1)){
 array_push($res1, array(
 $row2['username2'])
 );
 }
echo json_encode($res1);
?>


Source: stackoverflow-php

Push all data of Array of Strings into new array javascript .

I have a array of string Like this ,

"6:",350,e408,aeb"
"7:",350,e408"
"8:",350,e408,aeb,aeb"

Mean 6th index of array have 3 strings with comma seperated . I now I want it to be like

newarray[

"6: "350"
"7: "e408,
"8: "aeb"

]

I tried this function var array = string.split(','); but its not applicable on this. And another method but as its array of String I am unable to find a solution .


Source: stackoverflow-javascript

javascript regular expression to grab the state of 2 characters that is always following a city and a comma

Seems that google api for returns city and state from a zip code is just poorly made as they return a json object with address_components of which all have array list of elements with long_name and short_name

Now that would be fine , except that i cannot count on the state because in 3rd or the 4th array. :/

The ONE thing that i do see in common is a formatted_address of which example is

formatted_address: "Lake Villa, IL 60046, USA"

Since that is the case then seems that a regex is what i want

GOAL

var city = "Lake Villa"
var state = "IL" 

I don’t want to replace…. here is some regex i was trying to work with

 var formatted_address = "Lake Villa, IL 60046, USA";
 alert(formatted_address.replace(/(.+)-([A-Z]{2})$/, "$1, $2").replace("-", " "));


Source: stackoverflow-javascript

PHP How to send email to 2D array

Below is the Data(array that I’m trying to loop through)..

mind you the [DIJF0BWTS5DVLL9N5] is converted to a email address.
I tried using Nested Foreach loop it still sends all products to each [DIJF0BWTS5DVLL9N5](retailers email)

Array
(
    [DIJF0BWTS5DVLL9N5] => Array
        (
            [0] => Array
                (
                    [name] => Cowbell Chocolate
                    [price] => 750
                    [image] => Cowbell_milk.png
                    [productid] => 303
                    [retailerid] => DIJF0BWTS5DVLL9N5
                    [quantity] => 1
                    [code] => JH8YZL
                )

            [1] => Array
                (
                    [name] => Grandmas Cookies
                    [price] => 160
                    [image] => 0.036373001403792407.jpg
                    [productid] => 203
                    [retailerid] => DIJF0BWTS5DVLL9N5
                    [quantity] => 1
                    [code] => JH8YZL
                )

            [2] => Array
                (
                    [name] => Nido Milk
                    [price] => 800
                    [image] => 1498239307_nido.jpg
                    [productid] => 302
                    [retailerid] => DIJF0BWTS5DVLL9N5
                    [quantity] => 1
                    [code] => JH8YZL
                )

        )

    [DG8FSXW65OHCWJU0S] => Array
        (
            [0] => Array
                (
                    [name] => Barbaras Oat Crunch
                    [price] => 680
                    [image] => 0.917743001403788143.jpg
                    [productid] => 199
                    [retailerid] => DG8FSXW65OHCWJU0S
                    [quantity] => 1
                    [code] => JH8YZL
                )

        )

    [DIIGL2G07Y9E16NUO] => Array
        (
            [0] => Array
                (
                    [name] => Mini-Wheats
                    [price] => 700
                    [image] => 0.104168001409581063.jpg
                    [productid] => 237
                    [retailerid] => DIIGL2G07Y9E16NUO
                    [quantity] => 1
                    [code] => JH8YZL
                )

            [1] => Array
                (
                    [name] => Gullon Digestive Mueshli
                    [price] => 420
                    [image] => 0.064033001466093176.jpg
                    [productid] => 267
                    [retailerid] => DIIGL2G07Y9E16NUO
                    [quantity] => 1
                    [code] => JH8YZL
                )

        )

    [DKIK83VSGBJ8G1Q3O] => Array
        (
            [0] => Array
                (
                    [name] => chapagetti
                    [price] => 900
                    [image] => chapagetti.jpg
                    [productid] => 307
                    [retailerid] => DKIK83VSGBJ8G1Q3O
                    [quantity] => 1
                    [code] => JH8YZL
                )

        )

)


Source: stackoverflow-php

underscorejs – Group objects by property and print them

I have this array:

var ty = [
    {
      "Language": "en-GB",
      "Section": "Sales",
      "ItemName": "Type",
      "Texts": "Having selected the account heading select the calculation ..."
    }, 
    {
      "Language": "en-GB",
      "Section": "Sales",
      "ItemName": "Try",
      "Texts": "This is not happenning tho ..."
    },
    {
      "Language": "en-GB",
      "Section": "Taxes",
      "ItemName": "Save",
      "Texts": "The Master Tax Table has been pre populated with the current UK, ..."
    }];

and i need to group it in a way that according to the section it will contain all the properties that have the same section, like this:

[
    {section: 'Sales', ItemName: ['Type', 'Try'] Texts: ["Having selected the account heading select the calculation ...", "This is not happenning tho."]},

    {section: 'Taxes', ItemName: ['Type'] Texts: ['Having selected the account heading select the calculation.']}
]

So When I print it it will print just the text of each section.

This is the code I have so far:

var log = function(contents) {
  if (_.isArray(contents)) {
    _.each(contents, function(e, i, l) {
      log(e);
      $('#result');
      $('#result').append('</br></br>');
    });
  } else {
    console.log(contents);
    $('#result').append(contents);
  }
};

var ty = [
{
  "Language": "en-GB",
  "Section": "Sales",
  "ItemName": "Type",
  "Texts": "Having selected the account heading select the calculation ..."
}, 
{
  "Language": "en-GB",
  "Section": "Sales",
  "ItemName": "Try",
  "Texts": "This is not happenning tho ..."
},
{
  "Language": "en-GB",
  "Section": "Taxes",
  "ItemName": "Save",
  "Texts": "The Master Tax Table has been pre populated with the current UK, ..."
}];
var out = [];
_.groupBy(ty.Section, function(item){
    section: item.Section
    _.each(ty, function(item) {
    var hold = {};
    hold.options = {};
    hold.options.section[item.ItemName] = {
        text: item.Texts,
    };
    out.push(hold)
    });
});
log(out);

I have tried:

//More code above
_.each(ty, function(item) {
    iName: item.itemName;
    var hold = {};
    hold.options = {};
    hold.options.section.iName = {
        text: item.Texts,
    };
    out.push(hold)

but still it won’t print anything. in my dev tools it doesn’t show anything.

any tips?


Source: stackoverflow-javascript

How to convert Array to JSON

need your help about this one…
how can i convert this arrays to json code…

here’s my code:

$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);

// Will dump a beauty json :3
var_dump(json_decode($result, true));

$result = file_get_contents($url);
// Will dump a beauty json :3
var_dump(json_decode($result, true));

enter image description here


Source: stackoverflow-php

Javascript function. What is missing?

Write a program to find count of the most frequent item of an array.

Assume that input is array of integers.

Ex.:

input array: [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]
ouptut: 5
Most frequent number in example array is -1. It occurs 5 times in input array.

Here is my code:
function mostFrequentItemCount(collection) {

var copy = collection.slice(0);

for (var i = 0; i < collection.length; i++) {
 var output = 0;
 for (var x = 0; x < copy.length; x++) {
   if (collection[i] == copy[x]) {
 output++; 
}
}
}
  return output; 
 }

It seems to be just counting the reoccurrence of the first number in the array not the one that occurs the most. I can’t figure out how to make it count the most occurring one.


Source: stackoverflow-javascript

RxJS update Observable array items on the fly

Im using GeoFire in an Ionic 2/Firebase APP. The main screen function gets all the users that are close by as follows, This gets fed to an ngFor loop as an array.

The issue: If one of the users details change, for instance if they change their name, then a duplicate user gets added to the array rather than the actual user getting updated. Im not sure how to work this into this function.

public outputUsersCloseToMe() : Observable<Array<displayAllUsers>> {

    const currUsr = this.firebaseInit().auth().currentUser.uid

    let availableUsers = <Array<displayAllUsers>>[];

    const loc = this.firebaseInit().database().ref("users")
                                .child(currUsr)
                                .child('profile')
                                .child('lastKnownLocation');

    loc.once('value').then( (snapshot) => {
        let geoQuery = this.geoFire.query({
            center: [snapshot.val().lat, snapshot.val().lng],
            radius: 12.0//kilometers
        });
        geoQuery.on("key_entered", (key, location, distance) => {
            this.firebaseInit().database().ref('users').child(key).child('profile').on('value', (userprofile) => {  
                if( userprofile.val() ) {
                    availableUsers.push({ 
                        id: userprofile.val().id,                        
                        gender: userprofile.val().gender,
                        distance: distance.toFixed(2),
                        location: location,
                        firstName: userprofile.val().firstName,                        
                    });        
                }
            }); 
        });
    });
    return Observable.from([availableUsers]).map(val => val); 
}

and the template is similar to the following

        
{{ usr?.id }}


Source: stackoverflow-javascript

Sort JavaScript array by 3 values

I’d like to sort this JavaScript array by three values, but I can’t seem to figure out how to sort by more than one property at a time.

The requirements are:

  1. featured items should be at the very top
  2. Then items with no name (null)
  3. Then items with a name that are not featured
  4. Sort everything by createdAt in descending order (newest first)

This is the array:

var items [
    { name: 'foo-1', featured: true,  createdAt: 1493000001 },
    { name: null,    featured: false, createdAt: 1493000003 },
    { name: 'foo-3', featured: true,  createdAt: 1493000002 },
    { name: 'foo-4', featured: false, createdAt: 1493000004 },
    { name: 'foo-5', featured: false, createdAt: 1493000005 },
];

The result should be:

[
    { name: 'foo-3', featured: true,  createdAt: 1493000002 },
    { name: 'foo-1', featured: true,  createdAt: 1493000001 },
    { name: null,    featured: false, createdAt: 1493000003 },
    { name: 'foo-5', featured: false, createdAt: 1493000005 },
    { name: 'foo-4', featured: false, createdAt: 1493000004 },
]


Source: stackoverflow-javascript