从对象填充模型值。

时间:2018-09-25 09:41:53

标签: javascript arrays json reactjs loops

我正在尝试创建一个函数,该函数接收一个数组和一个对象,并像这样返回两者的组合。

fruits: [
  {
    name: apple,
    seeds: ''
  },
  {
    name: grape,
    seeds: ''
  },
  { name: banana,
    seeds: ''
  },
]

const seedData = {
  apple: 'yes',
  banana: 'yes',
  grape: 'no',
}

setSeedData = (fruits, seedData) => {
  return completedFruits
}

想要的结果是这样的:

fruits: [
  {
    name: apple,
    seeds: 'yes'
  },
  {
    name: grape,
    seeds: 'yes'
  },
  { 
    name: banana,
    seeds: 'no'
  },
]

我的问题是:如何创建函数setSeedData?返回的De数组应替换当前的fruits数组。

3 个答案:

答案 0 :(得分:2)

您基本上可以在数组上映射并返回更新的数据

const fruits= [
  {
    name: 'apple',
    seeds: ''
  },
  {
    name: 'grape',
    seeds: ''
  },
  { name: 'banana',
    seeds: ''
  },
]

const seedData = {
  apple: 'yes',
  banana: 'yes',
  grape: 'no',
}

setSeedData = (fruits, seedData) => {
  return fruits.map(fruit=> ({...fruit, seeds: seedData[fruit.name]}));
}

console.log(setSeedData(fruits, seedData));

答案 1 :(得分:1)

您可以使用.forEach()遍历数组并添加属性:

const fruits = [
  {name: 'apple', seeds: ''},
  {name: 'grape', seeds: ''},
  {name: 'banana', seeds: ''}
];

const seedData = {
  apple: 'yes',
  banana: 'yes',
  grape: 'no'
};

const setSeedData = (arr, obj) => (arr.forEach((o) => (o.seeds = obj[o.name])), arr);

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

答案 2 :(得分:1)

您可以映射到fruits上,并通过使用seeds键值seedData查找name对象来更新fruits键。 / p>

const fruits = [
  {
    name: 'apple',
    seeds: ''
  },
  {
    name: 'grape',
    seeds: ''
  },
  { name: 'banana',
    seeds: ''
  },
];

const seedData = {
  apple: 'yes',
  banana: 'yes',
  grape: 'no',
}

setSeedData = (fruits, seedData) => {
  return fruits.map(fruit => {
    return {...fruit, seeds: seedData[fruit.name]}
  })
}

console.log(setSeedData(fruits, seedData))