javascript按键过滤,并将键的值映射到另一个对象的新对象键

时间:2018-03-03 17:36:18

标签: javascript arrays object ecmascript-6

我通过基于一些允许的键过滤键来构造一个对象:

#remove \xef\xbb\xb
#https://github.com/pandas-dev/pandas/issues/4793
df = pd.read_csv(file, encoding="utf-8-sig")
#df.columns = df.columns.str.strip()

df['email_addresses'] = df['email_addresses'].apply(lambda x: [x])
update_contact = {"import_data" : df.to_dict(orient='records'),  "lists" : [1]}
print (update_contact)
{'import_data': [{'email_addresses': ['test@test.com'], 
                  'first_name': 'test', 
                  'last_name': 'test'}, 
                 {'email_addresses': ['Jane@Doe.com'], 
                  'first_name': 'Jane', 
                  'last_name': 'Doe'},
                 {'email_addresses': ['John@Smith.com'], 
                  'first_name': 'John', 
                  'last_name': 'Smith'}],
  'lists': [1]}

但是,我想从一个键/值配对对象中获取具有漂亮键名的新对象的键:

const configObject = { 
  key1: 'value1', key2: 'value2', key3: 'value3', key4: 'value4'
};
const allowed = ['key1', 'key3'];

const filtered = Object.keys(configObject)
  .filter(key => allowed.includes(key))
  .reduce((obj, key) => {
    obj[key] = configObject[key];
    return obj;
  }, {});

console.log(filtered) // { key1: 'value1', key3: 'value3' }

如何实现此目标以获得以下结果:

const allowed = [{'key1': 'keyOne'}, {'key3': 'keyThree'}];

5 个答案:

答案 0 :(得分:2)

您可以获取keys对象的条目并映射新属性。

var configObject = { key1: 'value1', key2: 'value2', key3: 'value3', key4: 'value4' },
    allowed = [{'key1': 'keyOne'}, {'key3': 'keyThree'}],
    filtered = Object.assign(
        ...allowed.map(o => 
            Object.assign(...Object.entries(o).map(([o, n]) =>
                ({ [n]: configObject[o] })))
        )
    );

console.log(filtered);

使用reduce

var configObject = { key1: 'value1', key2: 'value2', key3: 'value3', key4: 'value4' },
    allowed = [{'key1': 'keyOne'}, {'key3': 'keyThree'}],
    filtered = allowed.reduce((r, o) => {
        Object.entries(o).forEach(([o, n]) => r[n] = configObject[o]);
        return r;
    }, {});

console.log(filtered);

答案 1 :(得分:2)

您可以使用allowed作为字典,而不仅仅是列表:

const configObject = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3',
  key4: 'value4'
};
const allowed = {'key1': 'keyOne', 'key3': 'keyThree'};
const filtered = Object.keys(configObject)
  .filter(key => Object.keys(allowed).includes(key))
  .reduce((obj, key) => {
    obj[allowed[key]] = configObject[key];
    return obj;
  }, {});

console.log(filtered) // "keyOne": "value1", "keyThree": "value3" }

答案 2 :(得分:1)

您可以使用Array.reduce()来迭代allowed数组,并使用configObject上存在的键构建新对象:



const configObject = { key1: 'value1', key2: 'value2', key3: 'value3', key4: 'value4' };
const allowed = [{'key1': 'keyOne'}, {'key3': 'keyThree'}, 'key2', 'key5']; // I've added key2 as string, and the non existing key5

const result = allowed.reduce((r, o) => {
  // get the key and alias from an object or string
  const [key, alias] = typeof o === 'object' ? Object.entries(o)[0] : [o, o];
  
  if(key in configObject) { // if key exists in configObject
    r[alias] = configObject[key]; // assign it to r;
  }
  
  return r;
}, {});

console.log(result);




答案 3 :(得分:1)

只需更改对象的允许数组并使用相同的逻辑



const configObject = { 
  key1: 'value1', 
  key2: 'value2', 
  key3: 'value3', 
  key4: 'value4'
};

const allowed = {
  key1: 'keyOne',
  key3: 'keyThree'
};
const allowedKeys = Object.keys(allowed)

const filtered = Object.keys(configObject)
  .filter(key => allowedKeys.includes(key))
  .reduce((obj, key) => {
    obj[allowed[key]] = configObject[key];
    return obj;
  }, {});

console.log(filtered) 




答案 4 :(得分:1)

如果您只想从特定数字中获取漂亮的名称,请使用正则表达式:

/([a-z]+)(\d+)/i

适用于此keywhatever1111key1anotherkey2等任何关键字,依此类推。

var prettyOnes = {
  '1': 'One',
  '2': 'Two',
  '3': 'Three',
  '11': 'Eleven'
};

const configObject = { 
  key1: 'value1', key2: 'value2', key3: 'value3', whatever11: 'value11'
};
const allowed = ['key1', 'key3', 'whatever11'];

const filtered = Object.keys(configObject)
  .filter(key => allowed.includes(key))
  .reduce((obj, key) => {
    var [_, pre, pretty] = key.match(/([a-z]+)(\d+)/i);
    obj[`${pre}${prettyOnes[pretty]}`] = configObject[key];
    return obj;
  }, {});

console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }