2016-11-18 46 views
0

我有這個函數需要一個包含搜索對象數組的json參數。從數組中提取屬性

function receiveSearch(search, json) { 
    return { 
     type: RECEIVE_SCHOOL_SEARCH, 
     items: json.packages, 
     receivedAt: Date.now(), 
     search: Object.assign({}, search, { next: json.next, start: search.next }), 
    }; 
} 

json 財產的樣子:

>0:Object 
>1:Object 
>2:Object 
>3:Object 
...{ more } 

我想從JSON即namesuburb返回search對象的兩個屬性。我該怎麼做呢?我寧願使用像lodash/ramda /下劃線整齊的東西,但普通的js很好。

而且每個對象都包含以下屬性:

id:"10360" 
centreId:776 
name:"ABBOTSFORD" 
suburb:"TARNEIT" 
+0

你試過了什麼? – nicovank

回答

0

使用的JavaScript可能使其中只包含必需的屬性的新對象,並返回到您問題的最簡單的解決方案。

只是假設您的JSON是這樣的:

var x = {search:{id:"10360",centreId:776,name:"ABBOTSFORD",suburb:"TARNEIT"},otherProp:val} 

爲了得到所需的性能,可以使其他功能與所需的字段返回對象:

function ReturnRequiredPropertyObject(anyObj) 
{ 
    var newObj = {}; 
    newObj.search = {}; 
    newObj.search.name = anyObj.search.name; 
    newObj.search.suburb = anyObj.search.suburb; 
    return newObj; 
} 

你可以把上面的代碼在循環中,如果您正在獲取搜索對象的數組。

爲了使上面的代碼一般,我們可以做到以下幾點:

function ReturnRequiredPropertyObject(anyObj,requiredPropertyArray) 
{ 
    var newObj = {}; 
    for(var counter = 0;counter<requiredPropertyArray.length;counter++) 
    { 
     newObj[requiredPropertyArray[counter]] = anyObj[requiredPropertyArray[counter]]; 

    } 
    return newObj; 
} 

希望這會有所幫助。

0

好解決。

回答is

_.map(json,_.partialRight(_.pick,['name','suburb']));