Image

JSON

JS Var to JSON & vice-versa

function getObj() {
  var arrA = [22,43], arrB = [];
  return {
   ar1:arrA, 
   ar2:arrB
  };
}
var arr = getObj().ar1;
console.log(arr);

var arr1 = [1,2];
var arr2 = [3,4];

var obj = {a:arr1,b:arr2};

console.log(JSON.stringify(obj)); // {"a":[1,2],"b":[3,4]}
console.log(JSON.stringify(arr2)); // [3,4]

// adding top node to existing obj
var withPref = {'pref' : obj}

console.log(JSON.stringify(withPref)); // {"pref": {"a":[1,2], "b":[3,4]} }

var arr = (obj.a).concat(obj.b);
console.log(arr); // plain js array: [1, 2, 3, 4]

var jane = {"person":[{"id":121},{"title":"Jane"}]};

All About JSON Manipulation

<!DOCTYPE html>
<html >
  <head>
    <meta charset="UTF-8">
	<style>
	html,body {
		margin: 5px 0px 0px 5px;
		padding: 10px 0px 0px 0px;
	}
	span {
		border-radius: 3px;
		background: #220;
		color: #fff;
		padding: 10px;
	}
	</style>
  </head>

  <body>
    <div class="content"></div>
    <script src='jquery3.1.1.js'></script>

	<script type="text/javascript">
	$( "div.content" ).html("<span>Hello Again! I will exapnd</span>");
	$( "div.content span" ).append("&nbsp; > ABC" );
	
	var arry1 = [];
	var temp = {
		"gpc": [
          {
            "top": "Top1",
            "gmp": [
              {"name": "1. Basic Acc Srv"},
              {"name": "jquery"},
              {"name": "json"}
            ]
          },
			    {
            "top": "Top2",
            "gmp": [
              {"name": "1. Basic Acc Srv"},
              {"name": "ember"},
              {"name": "Top1"}
            ]
          }
		]
	};

function getObjects(obj, key, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getObjects(obj[i], key, val));    
        } else 
        //if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not)
        if (i == key && obj[i] == val || i == key && val == '') { //
            objects.push(obj);
        } else if (obj[i] == val && key == ''){
            //only add if the object is not already in the array
            if (objects.lastIndexOf(obj) == -1){
                objects.push(obj);
            }
        }
    }
    return objects;
}

function getValues(obj, key) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getValues(obj[i], key));
        } else if (i == key) {
            objects.push(obj[i]);
        }
    }
    return objects;
}

function getKeys(obj, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
			objects = objects.concat(getKeys(obj[i], val));
        } else if (obj[i] == val) {
			objects.push(i);
        }
    }
    return objects;
}


// then to get the JSON string
if(arry1.length === 0) {
  // console.log("empty arry");
} else {
  var strJSON = JSON.stringify({gpc: arry1});
  // console.log('New::: \n'+strJSON );
}

// console.log('Org::: \n'+JSON.stringify(temp));
var obj1 = getObjects(temp,'top','Top1');
var obj2 = getObjects(temp,'top','Top2');

var main = obj1.concat(obj2);

console.log(JSON.stringify(main));
	</script>
  </body>

</html>

adding a parent node

Stack Answer

Concat

Pen

See the Pen parse json by Hamzeen H (@hamzeen) on CodePen.

https://production-assets.codepen.io/assets/embed/ei.js

JSFiddle

http://jsfiddle.net/hamzeen/dw3q67md/

filter component

1. All urls to 1 route

Router.map(function() {
  this.route('about', {path: '/'});
  this.route('about', { path: '/*wildcard' });
});

2. Dom Manipulation

// in any controller
Ember.$('#component-x').val('My Value');

3. Adapter: rental.js

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
  'namespace': 'api'
});

4. Template: index.hbs

<div class="jumbo">
  <div class="right tomster"></div>
  <h2>Welcome!</h2>
  <p>
    We hope you find exactly what you're looking for in a place to stay.
    <br>Browse our listings, or use the search box above to narrow your search.
  </p>
</div>

{{input value=filterText type='text' placeholder='Search City'}}
  {{#unless filteredResults.length}}
    <h4>no record matched your criteria</h4>
  {{/unless}}

  <ul>
    {{#each filteredResults as |item|}}
      <li>{{item.id}} {{item.attributes.city}}</li>
    {{/each}}
  </ul>

5. Route: index.js

import Ember from 'ember';

export default Ember.Route.extend({
  filterText: '',

  setupController(controller, model) {
    this._super(controller, model);
    controller.set('filterText', this.get('filterText'));
  },

  queryParams: {
    search: {
      refreshModel: true
    }
  },

  beforeModel: function(transition) {
    // console.log('before model: '+transition.queryParams.search);
    this.set('filterText', transition.queryParams.search);
  },

  model: function(params) {
    var endPoint = 'http://localhost:4200/api/deals';
    var results = [];

    endPoint = (params.search)? endPoint+'/city='+params.search : endPoint;

    $.ajax({
      url: endPoint,
      type: 'GET',
      accepts: 'application/json',
      success: function(data) {
        if(data.rentals) {
          data.rentals.forEach(function(deal) {
            results.addObject(deal);
          });
        } else if(data.data === 'no records found'){
          console.log('No results found');
        } else {
          data.data.forEach(function(deal) {
            results.addObject(deal);
          });
        }
      },
      error: function() {
          console.log('DEBUG: GET Deals Failed');
      },async:false
    });
    return results;
  }
});

6. Controller: index.js

import Ember from 'ember';

export default Ember.Controller.extend({
  queryParams: ['search'],

  onFilterTextChange: function() {
    Ember.run.debounce(this, this.applyFilter, 0);
  }.observes('filterText'),

  applyFilter: function() {
    this.set('search', this.get('filterText'));
    console.log('search set: ' + this.get('search'));
  },
  
  filteredResults: function() {
    return this.get('model');
  }.property('search'),
});

7. Mock Response(http-mock): rentals.js

/*jshint node:true*/
module.exports = function(app) {
  var express = require('express');
  var rentalsRouter = express.Router();
  var rentals = [
      {
        type: 'rentals',
        id: 1,
        attributes: {
          title: 'Grand Old Mansion',
          owner: 'Veruca Salt',
          city: 'San Francisco',
          type: 'Estate',
          bedrooms: 15,
          image: 'https://upload.wikimedia.org/wikipedia/commons/c/cb/Crane_estate_(5).jpg'
        }
      }, {
        type: 'rentals',
        id: 2,
        attributes: {
          title: 'Urban Living',
          owner: 'Mike Teavee',
          city: 'Seattle',
          type: 'Condo',
          bedrooms: 1,
          image: 'https://upload.wikimedia.org/wikipedia/commons/0/0e/Alfonso_13_Highrise_Tegucigalpa.jpg'
        }
      }, {
        type: 'rentals',
        id: 3,
        attributes: {
          title: 'Downtown Charm',
          owner: 'Violet Beauregarde',
          city: 'Portland',
          type: 'Apartment',
          bedrooms: 3,
          image: 'https://upload.wikimedia.org/wikipedia/commons/f/f7/Wheeldon_Apartment_Building_-_Portland_Oregon.jpg'
        }
      }
    ];

  rentalsRouter.get('/', function(req, res) {
    res.send({
      rentals
    });
  });


  rentalsRouter.post('/', function(req, res) {
    res.status(201).end();
  });

  /*rentalsRouter.get('/:id', function(req, res) {
    res.send({
      '':req.params
    });
  });*/

  rentalsRouter.get('/:city', function(req, res) {
    let val = req.params.city.split("=");
    let filteredRentals = rentals.filter(function(i) {
      return i.attributes.city.toLowerCase().indexOf(val[1].toLowerCase()) !== -1;
    });

    if(filteredRentals.length>=1) {
      res.send({
        'data': filteredRentals
      });
    } else {
      res.send({
        'data': 'no records found'
      });
    }

    
  });

  rentalsRouter.put('/:id', function(req, res) {
    res.send({
      'rentals': {
        id: req.params.id
      }
    });
  });

  rentalsRouter.delete('/:id', function(req, res) {
    res.status(204).end();
  });

  // The POST and PUT call will not contain a request body
  // because the body-parser is not included by default.
  // To use req.body, run:

  //    npm install --save-dev body-parser

  // After installing, you need to `use` the body-parser for
  // this mock uncommenting the following line:
  //
  //app.use('/api/rentals', require('body-parser').json());
  app.use('/api/rentals', rentalsRouter);
};

Journal – publish bower package; setup ember mock

1. Publish Bower Package

Bower was started by twitter.
https://bower.io/docs/creating-packages/

2. Simple Ember App

Super Rentals

3. Mocks with EmberJS

EmberJS comes with ExpressJS (internally, http-mock) here are steps to setup a mock. Once setup it works like a real service & it actually be used to build REST API for your backend if it is fueled with real data.

  • generate ember project with ember-cli
  • generate an express route
    ember g http-mock destinations
  • to view: http://localhost:4200/api/destinations
  • Unlike fixtures, this helps you test your Adapter as well
  • setting up a mock response
// server/mocks/destinations.js
/*jshint node:true*/
module.exports = function(app) {
  var express = require('express');
  var destinationsRouter = express.Router();

  destinationsRouter.get('/', function(req, res) {
    res.send({
      'destinations': [
		{
			id:'001',
			loc: 'london'
		}, {
			id:'002', 
			loc: 'rotterdam'
		}, {
			id:'003', 
			loc: 'amsterdam'
		}
	  ]
    });
  });

  destinationsRouter.post('/', function(req, res) {
    res.status(201).end();
  });

  destinationsRouter.get('/:id', function(req, res) {
    res.send({
      'destinations': {
        id: req.params.id
      }
    });
  });

  destinationsRouter.put('/:id', function(req, res) {
    res.send({
      'destinations': {
        id: req.params.id
      }
    });
  });

  destinationsRouter.delete('/:id', function(req, res) {
    res.status(204).end();
  });

  // The POST and PUT call will not contain a request body
  // because the body-parser is not included by default.
  // To use req.body, run:
  //    npm install --save-dev body-parser

  // After installing, you need to `use` the body-parser for
  // this mock uncommenting the following line:
  //app.use('/api/destinations', require('body-parser').json());
  app.use('/api/destinations', destinationsRouter);
};