user2621221
user2621221

Reputation: 19

selecting object in data structure

How would you make an new object with just animal/weight key/value pairs from the following object?

{
    "Pigs": {
        "Weight": 6.2,
        "Price": 1.6
    },
    "Chicken": {
        "Weight": 5.8,
        "Price": 0.9
    },
  ...

Upvotes: 1

Views: 40

Answers (4)

wolver
wolver

Reputation: 197

It could be like this:

var animals = {animel1:"Pigs", animal2:"Chicken"};
animals.animel1.wight=6.2;
animals.animel1.price=1,6;
.
.
.

and so on

Upvotes: 0

Jérôme
Jérôme

Reputation: 292

Try something like this :

var objects = jQuery.parseJSON('{ "Pigs": { "Weight": 6.2, "Price": 1.6 }, "Chicken": { "Weight": 5.8, "Price": 0.9 }}');

var animals = [];

for (object in objects) {
    animals[object] = objects[object].Weight;
}

Upvotes: 0

kaytrance
kaytrance

Reputation: 2757

Like this:

var a = {
    "pigs" :   { "Weight": 6.2, "Price": 1.6 },
    "Chicken": { "Weight": 5.8, "Price": 0.9 }
}

Upvotes: 0

Royi Namir
Royi Namir

Reputation: 148624

Try this :

 var a={ "Pigs": { "Weight": 6.2, "Price": 1.6 }, "Chicken": { "Weight": 5.8, "Price": 0.9 }}
 var g={};

 for (var o in a)
  {
    g[o]=a[o].Weight;
  }

 console.log(g) //Object {Pigs: 6.2, Chicken: 5.8} 

Upvotes: 2

Related Questions