在对象中搜索字符串并形成对象数组

时间:2019-12-22 17:04:00

标签: javascript lodash

我需要在对象中搜索字符串并形成对象数组

key = {
  ID: '1',
  NAME: 'KEN',
  DEPT1: 'CSE',
  DEPT2: 'IT',
  DEPT3: 'NA',
  EMAIL: 'E@T.com'
}

输出:

[{"DEPT1":"CSE"},{"DEPT2":"IT"}]

对此进行了尝试,但给出了未定义的

var search = arr.push(_.findKey(key, _.curry(_.eq, 'CSE')));

console.log(search)

4 个答案:

答案 0 :(得分:4)

例如:

var result = Object.entries(key).reduce((result, [key, val]) => {
    if(key.match(/dept[12]/i)) result[key] = val;
    return result
}, []) // [{"DEPT1":"CSE"},{"DEPT2":"IT"}]

答案 1 :(得分:2)

使用lodash函数的最简单方法

const searchValues = Set('CSE', 'IT')
const arr = _.toPairs(obj).filter(([key, val]) => 
    searchValues.has(val)).map(([key, val]) => ({[key]: val}))

答案 2 :(得分:1)

尝试一下:

搜索每个关键字:

function search(keyword) {
  key = {
    ID: '1',
    NAME: 'KEN',
    DEPT1: 'CSE',
    DEPT2: 'IT',
    DEPT3: 'NA',
    EMAIL: 'E@T.com'
  }

  for (const k in key) {
    if (key[k] === keyword) {
      return ({
        [k]: key[k]
      })
    }
  }

  return null
}

console.log(search('CSE'))


搜索一组关键字:

function search(keywords) {
  const key = {
    ID: '1',
    NAME: 'KEN',
    DEPT1: 'CSE',
    DEPT2: 'IT',
    DEPT3: 'NA',
    EMAIL: 'E@T.com'
  }

  return Object.entries(key).reduce( (acc, [k, v]) => {
    return keywords.includes(v) 
    ? [...acc, { [k]: v } ] 
    : acc; 
  }, [])
}

const input = ['CSE', 'IT']
console.log(search(input))

答案 3 :(得分:1)


#...
dataset = pd.read_csv('data.csv')

# drop nulls and dublicates
# use fields to keep for your analysis both features and target
# e.g. FIELDS_TO_KEEP = ['a', 'b' ...]
dataset = dataset[FIELDS_TO_KEEP].dropna().drop_duplicates()

# get your feature X, target y
X = dataset[FIELDS_THAT_ARE_FEATURES]
y = dataset[['home_points', 'away_points']]

# ...