jtr109
2/2/2018 - 7:28 AM

my javascript lib

my javascript lib

JavaScript tools

/* Convert object into query */

const params = {color: 'red', minPrice: 8000, maxPrice: 10000};
const query = '?' + Object.keys(params)
  .map(k =>
    encodeURIComponent(k) + '=' + encodeURIComponent(params[k])
  )
  .join('&')
;
// encodeURIComponent encodes special characters like spaces, hashes
// query is now "color=red&minPrice=8000&maxPrice=10000"
/* ## Find the first matched object from array
 * 
 * ### Reference
 * 
 * - https://segmentfault.com/a/1190000013099221
 */

const posts = [
  {id: 1, title: 'Title 1'},
  {id: 2, title: 'Title 2'},
];
// find the title of post whose id is 1
const title = posts.find(p => p.id === 1).title;
/* ## Create map of product by id 
 * 
 * ### Reference
 * 
 * - https://segmentfault.com/a/1190000013099221
 */

let products = [
  {
    id: '123',
    name: '苹果'
  },
  {
    id: '345',
    name: '橘子'
  }
];

const productsById = products.reduce(
  (obj, product) => {
    obj[product.id] = product
    return obj
  },
  {}
);

console.log('result', productsById);