根据数组更改对象键

时间:2019-05-28 15:19:44

标签: javascript arrays object

我有一个对象和2个数组。我想根据object来更改arr2键,对象键和arr1的值是相同的,而数组中值的arr1arr2的位置是相同的,但不相同重视自己,而我不想问如何解决它,想知道我应该如何解决这个问题,谢谢您的时间

    const object = {
        name1: "some value",
        name3: "some value",
        name2: "some value",
        etc...}
    const arr1 = ["name1", "name2", "name3"]
    const arr2 = ["Name1", "Name2", "Name3"]

预期结果

    const newObject = {
        Name1: "some value",
        Name3: "some value",
        Name2: "some value",
        etc...}

6 个答案:

答案 0 :(得分:6)

我假设您正在按arr1arr2中的位置映射它们。 只需运行一个循环。

 const oldObject = {
        name1: "some value",
        name3: "some value",
        name2: "some value",
};

const arr1 = ["name1", "name2", "name3"];
const arr2 = ["Name1", "Name2", "Name3"];

var newObj = {};

for (var i = 0; i < arr2.length; i++) {
  newObj[arr2[i]] = oldObject[arr1[i]];
}

console.log(newObj);

答案 1 :(得分:3)

您可以使用reduce()

const object = {
        name1: "some value",
        name3: "some value",
        name2: "some value"
}

const arr1 = ["name1", "name2", "name3"]
const arr2 = ["Name1", "Name2", "Name3"]

const res = arr1.reduce((ac,a,i) => (ac[arr2[i]] = object[a],ac),{});
console.log(res)

答案 2 :(得分:3)

您可以使用reduce:

const object = {
  name1: "some value",
  name3: "some value",
  name2: "some value",
}
const arr1 = ["name1", "name2", "name3"]
const arr2 = ["Name1", "Name2", "Name3"]

const newObj = arr1.reduce((acc, value, index) => {
   acc[arr2[index]] = object[value]
   return acc
}, {})

console.log(newObj)

Reduce将遍历数组1,使用第二个数组中的相同索引来分配键,然后将第一个数组中的值与对象中的键进行比较,然后将其分配给新对象。

答案 3 :(得分:2)

您可以简单地执行以下操作:

var output={};
arr1.forEach(function(el, index){
   output[arr2[index]] = object[el];
}, this);

答案 4 :(得分:1)

假设您要保留新对象上arr1中不存在的键名。然后,您可以先在旧名称新名称之间创建一个Map(如果ES6不是您的选择,请在此处使用对象用于映射)。然后,您可以使用Object.entries()遍历Array.reduce()来生成新对象,其中仅将相关的键名映射到新的键名,其余的保留。

const obj = {
  name1: "some value 1",
  name3: "some value 2",
  name2: "some value 3",
  name4: "some value 4",
  name5: "some value 5"
}

const arr1 = ["name1", "name2", "name3"];
const arr2 = ["Name1", "Name2", "Name3"];

// Create a map between old names and new names.
let keysMap = new Map(arr1.map((key, idx) => [key, arr2[idx]]));

// Generate the new object, preserving non-mapped keys names.
let newObj = Object.entries(obj).reduce((acc, [k, v]) =>
{
    acc[keysMap.has(k) ? keysMap.get(k) : k] = v;
    return acc;
}, {});

console.log(newObj);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

答案 5 :(得分:1)

您可以先通过Array.map然后通过Object.fromEntries一行:

  const object = {
    name1: "some value A",
    name3: "some value B",
    name2: "some value C"
  }
  const old = ["name1", "name2", "name3"]
  const keys = ["Name1", "Name2", "Name3"]

let result = Object.fromEntries(old.map((x,i) => [keys[i], object[x]]))

console.log(result)