meallhour
meallhour

Reputation: 15571

How to modify array element within javascript object?

I am writing my code in NodeJS and have a object which looks as below.

const jsonData=
{
    "description": "description",
    "hosts": [
        "host1",
        "host2",
        "host3"
    ]
}

I want to delete all host elements execpt the first one.

Desired Output:

const jsonData=
{
    "description": "description",
    "hosts": [
        "host1"
    ]
}

And, the remaining elements should be moved to another variable.

const hostelementsExceptFirst = [ "host2", "host3" ];

I am performing the following operation but it is not giving desired output.

delete jsonData['hosts'];

Upvotes: 0

Views: 114

Answers (3)

Keith
Keith

Reputation: 24181

If you just want to mutate the array, you can use splice..

eg..

const jsonData =
{
    "description": "description",
    "hosts": [
        "host1", "host2", "host3"
    ]
}

const hostelementsExceptFirst = jsonData.hosts.splice(1);

console.log(jsonData);
console.log(hostelementsExceptFirst);

Upvotes: 4

gunwin
gunwin

Reputation: 4832

You can use Array.slice() to take a section of an array, and just reassign the hosts value afterwards.

const jsonData =
{
    "description": "description",
    "hosts": [
        "host1", "host2", "host3"
    ]
}

const remainers = jsonData.hosts.slice(1);
jsonData.hosts = [jsonData.hosts[0]];

console.log(jsonData);
console.log(remainers);

Upvotes: 2

Anton Neverov
Anton Neverov

Reputation: 311

const [firstValue, ...othersValues] = jsonData.hosts;

firstValue will be host1, and othersValues will be array with others

Upvotes: 1

Related Questions