admin管理员组文章数量:1300069
I am having an array like:
var arr = ["hello","world"]
// This array can contain any number of strings
Object like this:
var obj_arr = {
"abc-hello-1": 20,
"def-world-2": 30,
"lmn-lo-3": 4
}
I want to have an object which contains only those keys, which contains above array values as substrings. For eg:
Result will look like :
var result = {
"abc-hello-1": 20,
"def-world-2": 30,
}
I want to do something like this (using lodash) :
var to_be_ensembled = _.pickBy(timestampObj, function(value, key) {
return _.includes(key, "hello");
// here instead of "hello" array should be there
});
I am having an array like:
var arr = ["hello","world"]
// This array can contain any number of strings
Object like this:
var obj_arr = {
"abc-hello-1": 20,
"def-world-2": 30,
"lmn-lo-3": 4
}
I want to have an object which contains only those keys, which contains above array values as substrings. For eg:
Result will look like :
var result = {
"abc-hello-1": 20,
"def-world-2": 30,
}
I want to do something like this (using lodash) :
var to_be_ensembled = _.pickBy(timestampObj, function(value, key) {
return _.includes(key, "hello");
// here instead of "hello" array should be there
});
Share
Improve this question
edited May 11, 2020 at 19:37
Ori Drori
193k32 gold badges237 silver badges228 bronze badges
asked Aug 3, 2017 at 4:11
AshagAshag
8673 gold badges17 silver badges26 bronze badges
3 Answers
Reset to default 4With lodash you can use _.some()
to iterate the strings arrays, and to check if the key includes any of the strings.
const arr = ["hello", "world"]
const timestampObj = {
"abc-hello-1": 20,
"def-world-2": 30,
"lmn-lo-3": 4
}
const to_be_ensembled = _.pickBy(timestampObj, (value, key) =>
_.some(arr, str => _.includes(key, str))
);
console.log(to_be_ensembled);
<script src="https://cdnjs.cloudflare./ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Using only javascript you can acheive this using array forEach
& Object.Keys function
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)
Try this code
var result = _.map(arr, function(s){
return _.pickBy(timestampObj, function(v, k){
return new RegExp(s,"gi").test(k)
})
})
本文标签: jsonPick keys from object which contains specific string as substring in JavascriptStack Overflow
版权声明:本文标题:json - Pick keys from object which contains specific string as substring in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741655034a2390709.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论