1

I have an array that looks like this:

[{
    LocalBond:"0",
    LocalCash:"2.42",
    LocalEquity:"0",
    ForeignEquity: "4",
    ...
}]

What I want it look like:

[{
    Source: "LocalBond",
    Value: "0"
},
    Source: "LocalCash",
    Value: "2.42"
},
    Source: "LocalEquity",
    Value: "0"
},
{...}
]

I want to turn a single object into many objects. I also need the exclude the 'ForeignEquity' result.

I tried using _.map, and returning the fields I want, but I am struggling a bit. Am I on the right track? When I pass more than one parameter into my function, I don't get the desired result.

1
  • really the init array have a one object, or more objects? Commented Dec 29, 2016 at 8:05

1 Answer 1

1

The most simple code is pure javascript:

Using for..in access to the property of the object, and inside of the for loop build the array.

http://www.w3schools.com/jsref/jsref_forin.asp

Example:

https://jsfiddle.net/jewrsL8a/5/

var collection = [{
    LocalBond:"0",
    LocalCash:"2.42",
    LocalEquity:"0",
    ForeignEquity: "4"
}];

var result = [];

for (var property in collection[0]) {
    if(property!=='ForeignEquity'){
      result.push({'Source': property, 'Value': collection[0][property]});
    }
}

console.log(result);
Sign up to request clarification or add additional context in comments.

5 Comments

'Value' in this case should be collection[0][property]
let is not supportted well in some browsers
Thanks, the only problem is that I do not really want to do an IF Statement excluding 20 odd values. Same goes for including. Trying to figure a way around. The IF statement is last resort.
Thanks @allel for your answer. It gave me an idea. I did eventually end up using underscore. For the part about excluding values, I used underscores .contains filter and pushed the remaining values to an array. Worked perfectly!
@jae.phoenix you could also use underscore's pick or omit to select the keys you want

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.