Reputation: 497
I need to search for a string in an Object and form a array of object
key = {
ID: '1',
NAME: 'KEN',
DEPT1: 'CSE',
DEPT2: 'IT',
DEPT3: 'NA',
EMAIL: '[email protected]'
}
Output:
[{"DEPT1":"CSE"},{"DEPT2":"IT"}]
Tried this but it gives undefined
var search = arr.push(_.findKey(key, _.curry(_.eq, 'CSE')));
console.log(search)
Upvotes: 0
Views: 63
Reputation: 3032
The simpliest way using lodash functions
const searchValues = Set('CSE', 'IT')
const arr = _.toPairs(obj).filter(([key, val]) =>
searchValues.has(val)).map(([key, val]) => ({[key]: val}))
Upvotes: 2
Reputation: 4859
let key = {
"ID": "1",
"NAME": "KEN",
"DEPT1": "CSE",
"DEPT2": "IT",
"DEPT3": "NA",
"EMAIL": "[email protected]"
}
let output = []
const findKey = (searchKey) => {
Object.keys(key).forEach(key1 => {
key[key1] === searchKey ? output.push({
[key1]: key[key1]
}) : null
})
}
findKey("CSE")
console.log(output)
Upvotes: 1
Reputation: 9938
Try this:
Search for each keyword:
function search(keyword) {
key = {
ID: '1',
NAME: 'KEN',
DEPT1: 'CSE',
DEPT2: 'IT',
DEPT3: 'NA',
EMAIL: '[email protected]'
}
for (const k in key) {
if (key[k] === keyword) {
return ({
[k]: key[k]
})
}
}
return null
}
console.log(search('CSE'))
Search for an array of keywords:
function search(keywords) {
const key = {
ID: '1',
NAME: 'KEN',
DEPT1: 'CSE',
DEPT2: 'IT',
DEPT3: 'NA',
EMAIL: '[email protected]'
}
return Object.entries(key).reduce( (acc, [k, v]) => {
return keywords.includes(v)
? [...acc, { [k]: v } ]
: acc;
}, [])
}
const input = ['CSE', 'IT']
console.log(search(input))
Upvotes: 1
Reputation: 3834
Like this for example:
var result = Object.entries(key).reduce((result, [key, val]) => {
if(key.match(/dept[12]/i)) result[key] = val;
return result
}, []) // [{"DEPT1":"CSE"},{"DEPT2":"IT"}]
Upvotes: 4