Roman
Roman

Reputation: 81

Getting values from array of objects

I've got an array of objects

var arr1 = [{
        "amount": 700,
        "hits": 4,
        "day": 1
    },
    {
        "amount": 100,
        "hits": 7,
        "day": 4
    },
    {
        "amount": 500,
        "hits": 3,
        "day": 8
    }
];

What I need is to create a new array of objects, with key "param" in each object, and the value of "param" should be equals to "amount" field in arr1 objects.

Expected output:

var newArr = [{
        "param": 700
    },
    {
        "param": 100
    },
    {
        "param": 500
    }
];

Upvotes: 0

Views: 93

Answers (6)

Geek-Peer
Geek-Peer

Reputation: 11

Another way you can do this

var newArr=[];  
arr1.map(function(obj) {
newArr.push("param:"+obj.amaunt);
 });

Upvotes: 0

flott
flott

Reputation: 231

var newArr = []
arr1.forEach(obj => {
   newArr.push({param: obj.amount});
});

Upvotes: 2

Kumar
Kumar

Reputation: 280

Try this

arr1.forEach(function(data){            
          var obj = {"param": data.amount};          
          newArr.push(obj);          
        })

Fiddle here

Upvotes: 0

Yosvel Quintero
Yosvel Quintero

Reputation: 19070

You can user Array.prototype.map():

var arr1 = [{"amaunt": 700,"hits": 4,"day": 1}, {"amaunt": 100,"hits": 7,"day": 4}, {"amaunt": 500,"hits": 3,"day": 8}],
    newArr = arr1.map(function(elem) {
        return {param: elem.amaunt};
    });

console.log(newArr);

Upvotes: 3

Paarth
Paarth

Reputation: 590

You can try this

var arr1 = [
            {
                "amaunt": 700,
                "hits":4,
                "day":1
            },
            {
                "amaunt": 100,
                "hits":7,
                "day":4
            },
            {
                "amaunt": 500,
                "hits":3,
                "day":8
            }
        ];

    var newArr=[];
    arr1.forEach(function(item){
        newArr.push({"param":item.amaunt});
    });
    console.log(newArr);

Upvotes: 1

jcubic
jcubic

Reputation: 66478

Try using map:

var arr1 = [
  {
    "amaunt": 700,
    "hits":4,
    "day":1
  },
  {
    "amaunt": 100,
    "hits":7,
    "day":4
  },
  {
    "amaunt": 500,
    "hits":3,
    "day":8
  }
];
var arr2 = arr1.map(function(obj) {
  return {param: obj.amaunt};
});
console.log(arr2);

Upvotes: 2

Related Questions