0

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'];
1

3 Answers 3

4

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);

Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

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

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

1 Comment

This is a good start but doesn't alter the jsonData.hosts at all

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.