如何从JavaScript中的其他数组向数组中的对象内部的键添加值

时间:2018-09-06 11:20:53

标签: javascript

我有一个类似下面的数组 我试图通过替换数组内部对象内的null来添加一些值。 我要添加的值来自其他数组“ y”

let toBesubmitted = [
        {a: null, id: "a"},
        {b: null, id: "b"},
        {c: null, id: "c"},
        {d: null, id: "d"},
        {e: null, id: "e"}
      ]

另一个数组

let y= ["apple", "ball", "cat", "dog", "elephant"]

我该如何实现?

6 个答案:

答案 0 :(得分:3)

您可以通过在数组上使用forEach循环,并在y数组的特定item[item.id]处为index属性分配值来做到这一点:

let toBesubmitted = [
        {a: null, id: "a"},
        {b: null, id: "b"},
        {c: null, id: "c"},
        {d: null, id: "d"},
        {e: null, id: "e"}
      ]

let y= ["apple", "ball", "cat", "dog", "elephant"]

toBesubmitted.forEach((item, index) => item[item.id] = y[index]||null);

console.log(toBesubmitted)

答案 1 :(得分:0)

如果toBeSubmitted[0].a应该为y[0]并且id属性告诉我们要设置哪个属性,则可以执行一个简单的循环:

for (let i = 0; i < toBesubmitted.length; ++i) {
    toBesubmitted[i][toBesubmitted[i].id] = y[i];
}

示例:

let toBesubmitted = [
    {a: null, id: "a"},
    {b: null, id: "b"},
    {c: null, id: "c"},
    {d: null, id: "d"},
    {e: null, id: "e"}
];

let y = ["apple", "ball", "cat", "dog", "elephant"];

for (let i = 0; i < toBesubmitted.length; ++i) {
    toBesubmitted[i][toBesubmitted[i].id] = y[i];
}

console.log(toBesubmitted);

答案 2 :(得分:0)

虽然这不是最佳答案,但是请尝试以下方法:

    //print object
toBesubmitted.forEach(function(element, key){
    for(let e in element){
        if(e == Object.keys(element)[0])
            element[e] = y[key];
    }
});
Console.log(toBesubmitted);

答案 3 :(得分:-1)

假设toBesubmitted[index][key]y[index][0] 这个答案不依赖于索引的特定顺序。

let toBesubmitted = [
  { a: null, id: "a" },
  { b: null, id: "b" },
  { c: null, id: "c" },
  { d: null, id: "d" },
  { e: null, id: "e" }
];

let y= ["apple", "ball", "cat", "dog", "elephant"];

y.forEach( c => {
  const prop = toBesubmitted.find(tbs => tbs.id === c[0]);
  if(prop){
    prop[c[0]] = c;
  }
});

答案 4 :(得分:-1)

您还可以使用如下所示的reduce函数;

let toBesubmitted = [
{a: null, id: "a"},
{b: null, id: "b"},
{c: null, id: "c"},
{d: null, id: "d"},
{e: null, id: "e"}
];

let y = ["apple", "ball", "cat", "dog", "elephant"];

toBesubmitted.reduce( (acc,curr,idx) => curr[curr.id] = y[idx], {} );

console.log(toBesubmitted);

答案 5 :(得分:-2)

编辑

let toBesubmitted = [
    {a: null, id: "a"},
    {b: null, id: "b"},
    {c: null, id: "c"},
    {d: null, id: "d"},
    {e: null, id: "e"}
]

let y= ["apple", "ball", "cat", "dog", "elephant"]

toBesubmitted.forEach((item, index) => {
    Object.keys(item).forEach(key => {
        if (item[key] === null) {
            item[key] = y[index];
        }
    })
})

console.log(toBesubmitted);