使用es6数组函数迭代对象键以将选定的键替换为所需的键

时间:2019-02-11 12:11:17

标签: javascript ecmascript-6

我有一个要求,在我试图为其执行以下代码的对象中,用所需的键替换可用的键,后来我发现对于所需的输出过滤器使用不正确。因此,我需要帮助才能使用es6数组函数获得所需的结果。

const columns = Object.keys(someArray).filter((columnName) => {
      if (someCheck === "somecheck") {
        if (columnName === 'MyName') {
          const newcolumnName = `Pranav`;
          return newcolumnName;
        } else if (columnName === 'YourName') {
          const newcolumnName = `Alex`;
          return newcolumnName;
        }
      } else {
        return (columnName !== 'sometingelse') ? columnName : '';
      }
    }
    );

someArray如下:

someArray{
  abc:"djfhdjf",
  xyz:"ssss",
  MyName:"onename",
  YourName:"somename",
  sometingelse:'somevalue'
}

我希望columns是:

columns{
  abc:"djfhdjf",
  xyz:"ssss",
  Pranav:"onename",
  Alex:"somename",
  sometingelse:'somevalue'
}

请建议我如何实现上述预期输出?

注意:我不想在回调函数中使用function关键字以避免出现esltt错误

5 个答案:

答案 0 :(得分:1)

您可以过滤所需的替换密钥,并通过使用新密钥并删除旧密钥来替换密钥。

const
    object = { abc: "djfhdjf", xyz: "ssss", MyName: "onename", YourName: "somename", sometingelse: 'somevalue' },
    replacements = { MyName: 'Pranav', YourName: 'Alex', sometingelse: '' };

Object
    .keys(object)
    .filter(k => k in replacements)
    .forEach(k => {
        object[replacements[k]] = object[k];
        delete object[k];
    });
  
console.log(object);

要生成对象,您可以映射新对象并​​将其分配给单个对象。

const
    object = { abc: "djfhdjf", xyz: "ssss", MyName: "onename", YourName: "somename", sometingelse: 'somevalue' },
    replacements = { MyName: 'Pranav', YourName: 'Alex', sometingelse: '' },
    result = Object.assign(...Object
        .entries(object)
        .map(([k, v]) => ({ [k in replacements ? replacements[k] : k]: v }))
    );
  
console.log(result);

答案 1 :(得分:0)

我正在以空对象开始对某些数组的键进行归约。 ... acc扩展了简化对象中的所有属性。 ... {[keysMap [key] || key]:obj [key]}检查keyMap中是否存在当前键。如果存在,则使用该键(keysMap [key]),否则仅使用现有对象的键。(|| key)。希望有道理

    const renameKeys = (keysMap, obj) =>
       Object.keys(obj).reduce(
        (acc, key) => ({
          ...acc,
          ...{ [keysMap[key] || key]: obj[key] }
       }),
    {}
  )
  const columns = renameKeys({'MyName':'Pranav','YourName':'Alex'},someArray)

答案 2 :(得分:0)

这是我的方法,有点长的解决方案,但是它是有目的的,因此您可以看到如何在没有太多抽象的情况下简单地实现它:

const someArray = {
abc:"djfhdjf",
xyz:"ssss",
MyName:"onename",
YourName:"somename",
sometingelse:'somevalue'
}


let foo = Object.keys(someArray).map(key => {
  if(key === 'MyName') {
    return 'Alex'
  } else if(key === 'YourName') {
    key = 'Pranav'
  }
  return key;
})

let bar = Object.entries(someArray).map((el, i) => {
  el[0] = res[i];
  return el;
})

let baz = r.reduce((acc, el)=>{
  acc[`${el[0]}`] = el[1];
  return acc;
},{})
console.log(baz);

答案 3 :(得分:0)

const obj = {
  abc: 'djfhdjf',
  xyz: 'ssss',
  MyName: 'onename',
  YourName: 'somename',
  sometingelse: 'somevalue'
};

const newObj = Object.keys(obj).reduce((acc, key) => {
  if (key === 'MyName') {
  	acc.newMyName = obj[key];
  } else if (key === 'YourName') {
  	acc.newYourName = obj[key];
  } else {
  	acc[key] = obj[key];
  }
  
  return acc;
}, {});

console.log('newObj = ', newObj);

答案 4 :(得分:0)

您可以像这样使用.reduce。它使用了Nina提出的类似想法,即使用一个对象来保存您的替换物品。在这里,我使用了传播语法,将更改的键及其关联的值添加到累积的对象中。

const someArray = {abc: "djfhdjf", xyz: "ssss", MyName: "onename", YourName: "somename", sometingelse: 'somevalue'},
toUse = {MyName: "Pranav", YourName: "Alex"}, // define the keys you want to change and what they should change to

res = Object.keys(someArray).reduce((acc, key) => 
    ({...acc, [key in toUse ? toUse[key] : key]:someArray[key]})
, {});
console.log(res);