2017-01-26 148 views
1

我想找到一種簡單的方法來從嵌套數組中移動對象並將其移動到其父數組。如果你嘗試使用'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)); 
 
}

+2

包含[0]不是一個數組,它是一個對象。你應該'contains.splice(0,1)'而不是 – alebianco

+0

如果它不是'items [0] .contains.splice(0,1)' – Rajesh

回答

1

Array.prototype.splice()返回

含有缺失元素的數組。

要移動從嵌套數組某個對象到父級別可以使用以下的方法:

items.push(items[0].contains.splice(0, 1)[0]);