将数组添加为新的键值对

时间:2019-08-08 16:41:37

标签: javascript arrays

我有一个现有的数组,其中包含一系列项目的键值对:

resultsArray = [
  {
    parkName: "Central Park",
    owner: "NYC" 
  },
  {
    parkName: "Patterson Park",
    owner: "Baltimore"
  }
]

我想在每个值是一系列便利设施的项目中添加一个附加的键值对。例如:如果中央公园包括一个狗公园,缓跑径和篮球场,帕特森公园包括一个棒球场和娱乐中心,则在将便利设施添加到数组时,resultsArray现在看起来像:

resultsArray = [
  {
    parkName: "Central Park",
    owner: "NYC",
    amenities: "Dog Park", "Jogging Trail", "Basketball Courts"
   },
  {
    parkName: "Patterson Park",
    owner: "Baltimore",
    amenities: "Baseball Fields", "Recreation Center"
   }
]

我对Java语言还比较陌生,但是我已经为每个公园成功创建了一系列便利设施。然后,我尝试如下添加每个amenityArray:

resultsArray.push({
  amenities: amenityArray
});

但是,这没有给我我想要的东西。

有人可以演示如何将amenityArray添加为每个公园的键值对吗?

4 个答案:

答案 0 :(得分:0)

对于resultsArray中的每个对象,添加相应的舒适性。


for (let i = 0; i < resultsArray.length; i++) {
    resultsArray[i][i]['amenities'] = amenityArray[i];
}

一个更详细的版本是


for (let i = 0; i < resultsArray.length; i++) {
    let result = resultsArray[i];  // i is an index
    let innerResult = result[i];  // i is a key
    innerResult['amenities'] = amenityArray[i];
}

答案 1 :(得分:0)

迭代数组,并在内部对象中添加新的键值对。

注意::动态选择设施。

resultsArray = [{ 0: { parkName: "Central Park", owner: "NYC" } }, { 1: { parkName: "Patterson Park", owner: "Baltimore" } }];
amenities = { "0": "X Park, Y Park, Z Park", "1": "A Park, B park, C Park" };
[...resultsArray].forEach(token => {
    Object.keys(token).forEach(key => token[key]['amenities'] = amenities[key]);
})
console.log(resultsArray);

答案 2 :(得分:0)

您可以使用.forEach()遍历数组并根据索引设置各项:

var resultsArray = [{parkName: "Central Park",owner: "NYC"},{parkName: "Patterson Park", owner: "Baltimore"}]

var amenityArray = [["Dog Park", "Jogging Trail", "Basketball Courts"], ["Baseball Fields", "Recreation Center"]];

resultsArray.forEach((val, index) => {val.amenities = amenityArray[index]})

console.log(resultsArray)

答案 3 :(得分:0)

您可以使用map

const newArray = resultsArray.map((item, i) => {
  item[i].amenities = amenityArray[i];
  return item;
});

同样,您的数组结构看起来很怪异,您应该考虑删除那些多余的嵌套对象,然后迭代起来会更容易:

resultsArray = [{
    parkName: "Central Park",
    owner: "NYC"
  },
  {
    parkName: "Patterson Park",
    owner: "Baltimore"
  }
]

const newArray = resultsArray.map((item, i) => {
  item.amenities = amenityArray[i];
  return item;
});