Angel Sanchez Angel Sanchez - 6 months ago 13
Javascript Question

Manipulating objects arrays with Javascript

I have a function like this:

pickListSelect array
is has all id (numbers) to delete objects in
source array
, and
target array
it is to push elements deleted from
source array
.

function copy(pickListSelect, source, target) {

var i, id;

for (i = 0; i < pickListSelect.length; i++) {
id = pickListSelect[i];
source.splice(id,1);
}
pickListSelect = [];
}


So what I need is delete specific object from
source arra
y. I tried with that code but for example if I need to delete object with id=5, it only deleted item 5 from the list.

The structure of source array is this:

[Object, Object, Object, Object, Object, Object, Object, Object, Object]
0:Object
plantId:1
plantName:"Plant 1"

...the rest of others are similar object

Answer

You need to find plant in your source by plantId first, and then delete it from original array and push to target. Open console and it should log deleted plants:

var plants = [
    {
        plantId: 1,
        plantName: 'plant 1'
    },
    {
        plantId: 2,
        plantName: 'plant 2'
    },
    {
        plantId: 3,
        plantName: 'plant 3'
    },
    {
        plantId: 4,
        plantName: 'plant 4'
    }
];

function copy(pickListSelect, source, target) {
    var i, id, el;

    for (i = 0; i < pickListSelect.length; i++) {
        id = pickListSelect[i];
        el = findPlant(source, id);
        source.splice(source.indexOf(el), 1);
        target.push(el);
    }
}

function findPlant (arr, id) {
    return arr.filter(function (plant) {
        return plant.plantId == id
    })[0]
}

var test = [];

copy([2,3], plants, test);

console.log(test);

Comments