Alan Wells
Alan Wells

Reputation: 31300

Strip key values out of object array with javascript

I have an array with this data in it:

[
  {
    user1post2: {
        ad:"Car", ac:39500, af:"4", ah:"klgjoirt3904d", ab:"Acura", 
        ae:"2013  ACURA MDX  3.5L V6 AWD 6AT (294 HP)", ag:"Mint", aa:"Option2"
      },
    user1post1: {
      ad:"Truck", ac:6799, af:"3", ah:"ldkfldfjljKey", ab:"GMC", 
      ae:"1/2 Ton with plow", ag:"Mint Looks", aa:"Option1"
    }
  }
]

I need to strip out user1post2 and user1post1.

I've tried using something like this, but it doesn't work:

  var valu2 = values; //put current array into new variable `valu2`

  console.log(valu2.toSource()); //Log to console to verify variable
  var finalData = [];  //Create new array
  for (var name2 in valu2) {
    finalData.push(valu2[name2]);
  };

  console.log(finalData.toSource());

How do I strip out those key values user1post2: ?

When I check the length,

console.log("length is:" + values.length);

it indicates a length of 1, so if the count starts at zero, then that would be correct. I could set up a for loop that iterates from 0 to i.

I'm not sure what the syntax or property is to reference data inside the array.

Upvotes: 2

Views: 1013

Answers (2)

slapthelownote
slapthelownote

Reputation: 4279

Is this what you want?

values = [{
    user1post2: {
        ad: "Car",
        ac: 39500,
        af: "4",
        ah: "klgjoirt3904d",
        ab: "Acura",
        ae: "2013  ACURA MDX  3.5L V6 AWD 6AT (294 HP)",
        ag: "Mint",
        aa: "Option2"
    },
    user1post1: {
        ad: "Truck",
        ac: 6799,
        af: "3",
        ah: "ldkfldfjljKey",
        ab: "GMC",
        ae: "1/2 Ton with plow",
        ag: "Mint Looks",
        aa: "Option1"
    }
}]

out = [];
for(prop in values[0]) {
    out.push(prop);
}

console.log(out);

or are you trying to iterate over the actual data inside each property (i.e. loop over user1post2 to get the value ad: "Car" etc)?

Upvotes: 1

Nelson Menezes
Nelson Menezes

Reputation: 2094

You have an array with a single object within. The keys of that object are what you want as an array. So:

var val = [{ /*... your data ...*/ }];
var out = [];
var myBigObject = val[0];

for (var i in myBigObject) {
    if (myBigObject.hasOwnProperty(i)) {
        out.push(myBigObject[i]);
    }
}

console.log(out);

http://jsfiddle.net/5xuLJ/

Upvotes: 3

Related Questions