對象和數組的遍歷方法

obj遍歷:

for in,bash

for (var nextKey in nextSource) {   
    // Avoid bugs when hasOwnProperty is shadowed    
    if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {       
    to[nextKey] = nextSource[nextKey];    
}}複製代碼

Object.keys().forEach ui

Object.keys(filters).forEach(key => {  
    Vue.filter(key, filters[key]);
});複製代碼

const raw = {
  item1: { key: 'sdfd', value:'sdfd' },
  item2: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }
};

const allowed = ['item1', 'item3'];
//1
const filtered = Object.keys(raw)
  .filter(key => allowed.includes(key))
  .reduce((obj, key) => {
    obj[key] = raw[key];
    return obj;
  }, {});
//2
Object.keys(raw)
  .filter(key => !allowed.includes(key))
  .forEach(key => delete raw[key]);

console.log(raw);
console.log(filtered);複製代碼

arr遍歷:

forEach(value,index)、spa

map(value, index)、prototype

return categories.map(item => {  
    return {    
        label: item.category,    
        value: item.id,    
        children: parseChildCategory(item)  
    };
});複製代碼

for循環、 code

for in、 string

for of(value)it

相關文章
相關標籤/搜索