-2

I have an array called x. It contains objects with three fields. How can I make another array called xmini that is the same as x but with the field called c missing?

var  x = [
  { a : 1, b : 2, c : 3 },
  { a : 3, b : 4, c : 5 }
];
ppoliani
  • 4,792
  • 3
  • 34
  • 62
Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427
  • 1
    I was tempted to answer: `var xmini = [{a = 1, b = 2}, {a = 3, b = 4}];` – AnalogWeapon Feb 07 '14 at 16:22
  • What is the actual problem? – cookie monster Feb 07 '14 at 16:26
  • If all you need is for `c` to come back `undefined`, then you can use protoypal inheritance. `x.map(function(o) { return Object.create(o, {c:{value:undefined}}); });` Totally depends on how you're using the data. – cookie monster Feb 07 '14 at 16:29
  • You don't have an array with three fields but rather an array of objects, each of which has three fields. Furthermore I corrected your original array/object literal syntax which was just wrong. – Dexygen Feb 07 '14 at 16:30
  • @cookiemonster - I send the data back to the server. Needs to go back without any mention of a field c. – Samantha J T Star Feb 07 '14 at 16:42
  • 4
    It's a pity that you won't tell us what you have tried or the problem you are having, but if you are sending it to a server then one would assume that you `JSON.stringify` the array, so simply `JSON.stringify(x, ['a', 'b'])` – Xotic750 Feb 07 '14 at 17:01

1 Answers1

3

This method will not affect the original x object.

var xmini = [],
    tmpObj = {};

for (var i = 0; i < x.length; i++) {
    for (var key in x[i]) {
        if (key !== 'c') {
            tmpObj[key] = x[i][key];
        }
    }
    xmini.push(tmpObj);
    tmpObj = {};
}

You should try to be more specific about what you have tried and what you are trying to accomplish. Another valid answer to your question (as you phrased it) would be simply: var xmini = [{a = 1, b = 2}, {a = 3, b = 4}];, but I assumed you wanted a function to create this new object programmatically without changing the original object and without needing to know anything about the other properties of the original object.

AnalogWeapon
  • 550
  • 1
  • 4
  • 16