2

I have an object like this:

[ 
    { "number": 12, "string": "hi"},
    { "number": 40, "string": "bye"}
] 

I want:

{"number": [12, 40], "string": ["hi", "bye"]}

Or:

{"number": "12,40", "string": "hi,bye"}
1
  • what have you already tried? Commented Nov 22, 2018 at 11:52

5 Answers 5

3

You can use Array.prototype.reduce():

The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value.

Solution With Concatenated String:

var data = [ 
    { "number": 12, "string": "hi"},
    { "number": 40, "string": "bye"}
] 
data = data.reduce((a,c)=>{
  a.number = a.number + ',' +c.number;
  a.string = a.string + ',' +c.string;
  return a;
});
console.log(data);

Solution With Array:

var data = [ 
    { "number": 12, "string": "hi"},
    { "number": 40, "string": "bye"}
]

data = data.reduce((a,c)=>{
  a.number.push(c.number);
  a.string.push(c.string);
  return a;
}, {number:[],string:[]});
console.log(data);

Sign up to request clarification or add additional context in comments.

Comments

1

I have done this like so:

let array = [ 
    { "number": 12, "string": "hi"},
    { "number": 40, "string": "bye"}
];

let resultObject = {
    numbers: [],
  strings: []
}

for (let element of array) {
 resultObject.numbers.push(element.number);
 resultObject.strings.push(element.string);
}

console.log(resultObject);

Hope it helps :)

Comments

0

You can use Array.reduce() for that:

var arr = [ 
    { "number": 12, "string": "hi"},
    { "number": 40, "string": "bye"}
];
var res = arr.reduce((acc, item)=>{
  if(acc.number && acc.string){
    acc.number.push(item.number);
    acc.string.push(item.string);
  } else {
    acc = {
      number: [item.number],
      string: [item.string]
    }
  }
  return acc;
}, {});
console.log(res);

Comments

0

You could reduce the array and the entris of the object and collect all value with their key in an array without having hardcoded properties.

var array = [{ number: 12, string: "hi" }, { number: 40, string: "bye" }],
    result = array.reduce(
        (r, o) => Object.entries(o).reduce(
            (s, [k, v]) => ((s[k] = s[k] || []).push(v), s),
            r
        ),
        {}
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0

You can use lodash's _.mergeWith() to combine them:

const arr = [{ "number": 12, "string": "hi"}, { "number": 40, "string": "bye"}];

const result =_.mergeWith({}, ...arr, (s = [], o) => [...s, o]);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Comments

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.