-2

I have an obj in which need to swap title and id elements inside, priority remains in place.

const obj= [{id: 300, priority: 1, title: "title 1"}
            {id: 301, priority: 2, title: "title 2"}
            {id: 302, priority: 3, title: "title 3"}
            {id: 303, priority: 4, title: "title 4"}];

Should get this:

const obj= [{id: 301, priority: 1, title: "title 2"}
            {id: 300, priority: 2, title: "title 1"}
            {id: 302, priority: 3, title: "title 3"}
            {id: 303, priority: 4, title: "title 4"}];

1 Answers1

1

There is a swap operation in JS.

function swap(source, id1, id2) {
    if (parseInt(id1) > source.length || parseInt(id2) > source.length) {
        throw "Out of source range"
    }
    [source[id1].id, source[id2].id] = [source[id2].id, source[id1].id];
    [source[id1].title, source[id2].title] = [source[id2].title, source[id1].title];
}

obj = [{id: 300, priority: 1, title: "title 1"},
        {id: 301, priority: 2, title: "title 2"},
        {id: 302, priority: 3, title: "title 3"},
        {id: 303, priority: 4, title: "title 4"}];
swap(obj, 0, 1);
console.log(obj);

Remember this will overwrite the source object. If you want to return the copy you need to copy element in the function.

Daniel Hornik
  • 1,957
  • 1
  • 14
  • 33