2017-01-26 7 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]);