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
Add a ment  | 

3 Answers 3

Reset to default 4

With 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