拼接在数组中的嵌套对象

时间:2017-01-26 11:44:56

标签: javascript arrays object splice

我试图找到一种简单的方法从嵌套数组中移动对象并将其移动到其父数组。我一直在"拼接不是一个功能,"正如您所看到的,如果您尝试使用' moveItem()'功能。我不知道如何重写这个如此有用,如果它甚至被允许做这个事情。任何帮助表示赞赏。简而言之,我试图将对象从项目[0] .contains []移动到项目[]希望这是有道理的。



var items = [{
  itemIndex: 0,
  name: "a box of matches",
  examine: "The box is old and damp,you find a single match inside.",
  location: 0, // if location === 1000, items is in inventory.
  contains: [{
    itemIndex: 1,
    name: "a match",
    examine: "A single match.",
    location: 0,
    contains: [],
    hidden: true,
    collectable: true,
    useWith: 2,
    useWithFail: 0,
    useWithFailResponse: "the box is too damp to light the match",
    useWithSuccessResponse: null
  }], // Contain items inside items using array.
  hidden: false, // if hidden, item cannot show up in invetory or room inventory
  collectable: true,
  useWith: null, // Item that this item can be successfully used with - index or null
  useWithFail: 1, // Use with item that fails but has it's own unique fail message - index or null
  useWithFailResponse: "the box is too damp to light the match",
  useWithSuccessResponse: null
}, {
  itemIndex: 2,
  name: "a closed cupboard",
  examine: "You find a kitchen knife inside",
  location: 4,
  contains: [],
  hidden: false,
  collectable: false,
  useWith: null,
  useWithFail: null,
  useWithFailResponse: null,
  useWithSuccessResponse: "The match spaks into life!"
}, {
  itemIndex: 3,
  name: "a kitchen knife",
  examine: "It is old and rusty.",
  location: 4,
  contains: [],
  hidden: true,
  collectable: true,
  useWith: 1,
  useWithFail: null,
  useWithFailResponse: null,
  useWithSuccessResponse: "The match sparks into life!"
}, ];

function moveItem() {
  items.push(items[0].contains[0].splice(0, 1));
}




1 个答案:

答案 0 :(得分:1)

Array.prototype.splice()返回

  

包含已删除元素的数组。

要将某个对象从嵌套数组移动到父级别,请使用以下方法:

items.push(items[0].contains.splice(0, 1)[0]);
相关问题