SangHak Lee
SangHak Lee

Reputation: 33

javascript array-object convert one key, array value single object

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"}

Upvotes: 2

Views: 77

Answers (5)

Ori Drori
Ori Drori

Reputation: 192507

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>

Upvotes: 0

Mamun
Mamun

Reputation: 68933

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);

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386736

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; }

Upvotes: 0

IncrediblePony
IncrediblePony

Reputation: 752

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 :)

Upvotes: 1

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

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);

Upvotes: 0

Related Questions