Bazilby
Bazilby

Reputation: 79

Split JSON by elements/objects and create new JSON

I want to take a JSON string and split all the elements under value1 and form a new JSON string from the results.

My JSON string

[
    {
        "label": "1556015903109.00",
        "value1": "1.7481",
        "value2": "1.7489",
        "value3": "1.7375",
        "value4": "2.5631"
    },
    {
        "label": "1556015954378.00",
        "value1": "1.7481",
        "value2": "1.7336",
        "value3": "1.7477",
        "value4": "2.5631"
    },
    {
        "label": "1556016004213.00",
        "value1": "1.7481",
        "value2": "1.7336",
        "value3": "1.7426",
        "value4": "2.5631"
    },
    {
        "label": "1556016034313.00",
        "value1": "1.7481",
        "value2": "1.7489",
        "value3": "1.7426",
        "value4": "2.5631"
    }
]

I've already tried with a map

 var value1= results.map(item => item.value1);

But this gives the result like:

["1.7481", "1.7481", "1.7481", "1.7481"]

Whereas I need it to be

[
    {
        "value1": "1.7481"
    },
    {
        "value1": "1.7481"
    },
    {
        "value1": "1.7481"
    },
    {
        "value1": "1.7481"
    }
]

Upvotes: 2

Views: 164

Answers (2)

Nikhil
Nikhil

Reputation: 6643

var value1= results.map(item => item.value1);

In your map() method, you are returning item.value1, a string.

But since you want an object with value1 as property, you have return an object with value1 as property with item.value1 as its value.

var data = [ { "label": "1556015903109.00", "value1": "1.7481", "value2": "1.7489", "value3": "1.7375", "value4": "2.5631" }, { "label": "1556015954378.00", "value1": "1.7481", "value2": "1.7336", "value3": "1.7477", "value4": "2.5631" }, { "label": "1556016004213.00", "value1": "1.7481", "value2": "1.7336", "value3": "1.7426", "value4": "2.5631" }, { "label": "1556016034313.00", "value1": "1.7481", "value2": "1.7489", "value3": "1.7426", "value4": "2.5631" } ]; 

var results = data.map(item => ({
  "value1": item.value1
}));

console.log(results);

Upvotes: 2

Bilal Siddiqui
Bilal Siddiqui

Reputation: 3629

Very simple, just do like this:

let newData = [];
data.forEach(el => {
    newData.push({value1: el.value1});
});

Upvotes: 1

Related Questions