2017-08-03 18 views
0
specifc字符串作爲子

我有喜歡的數組:選號鍵包含在Javascript

var arr = ["hello","world"] 
// This array can contain any number of strings 

對象是這樣的:

var obj_arr = { 
     "abc-hello-1": 20, 
     "def-world-2": 30, 
     "lmn-lo-3": 4 
    } 

我想有這隻有那些包含對象鍵,它包含上面的數組值作爲子字符串。 對於如:

結果會是這樣的:

var result = { 
     "abc-hello-1": 20, 
     "def-world-2": 30, 
    } 

我想要做這樣的事情(使用lodash):

var to_be_ensembled = _.pickBy(timestampObj, function(value, key) { 
       return _.includes(key, "hello"); 
// here instead of "hello" array should be there 
      }); 

回答

2

您可以使用_.some()迭代字符串數組,並檢查密鑰是否包含任何字符串。

var arr = ["hello", "world"] 
 

 
var timestampObj = { 
 
    "abc-hello-1": 20, 
 
    "def-world-2": 30, 
 
    "lmn-lo-3": 4 
 
} 
 

 
var to_be_ensembled = _.pickBy(timestampObj, function(value, key) { 
 
    return _.some(arr, function(str) { // iterate the arr 
 
    return _.includes(key, str); // if one of the strings is included in the key return true 
 
    }); 
 
}); 
 

 
console.log(to_be_ensembled);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

3

僅使用JavaScript你可以使用數組forEach &達致這Object.Keys功能

var arr = ["hello", "world"] 
 

 

 
var obj_arr = { 
 
    "abc-hello-1": 20, 
 
    "def-world-2": 30, 
 
    "lmn-lo-3": 4 
 
} 
 

 
var resultObj = {}; 
 
// get all the keys from the object 
 
var getAllKeys = Object.keys(obj_arr); 
 
arr.forEach(function(item) { 
 
    // looping through first object 
 
    getAllKeys.forEach(function(keyName) { 
 
    // using index of to check if the object key name have a matched string 
 
    if (keyName.indexOf(item) !== -1) { 
 
     resultObj[keyName] = obj_arr[keyName]; 
 
    } 
 
    }) 
 
}) 
 
console.log(resultObj)

+0

感謝。任何奇特的方式使用lodash? – Ashag

2

試試這個代碼

var result = _.map(arr, function(s){ 
    return _.pickBy(timestampObj, function(v, k){ 
    return new RegExp(s,"gi").test(k) 
    }) 
})