-1

I have an array of objects with key-value pair, how to convert it to an object by reducing it to a single object by removing keys. I tried with map filter reduce but couldn't get the desired result. please help

const object = Object.assign({}, ...obj); // not working
const result = {};

Object.keys(object).forEach((key, index) => {
    result[`newObj${index + 1}`] = obj[key].map(item => ({[key]: item}));
}); // not working

Input

   obj = [{key: name, value: jack},{key: age, value: 10},{key: country, value: india},{key: state, value: Delhi}];

Output

{name:jack, age:10, country:india, state: Delhi}
Aayush Mall
  • 963
  • 8
  • 20
Vishnu Shenoy
  • 862
  • 5
  • 18

4 Answers4

3

Use forEach and destructuring

Update: Fixed based on Jan pointed out. Thanks @Jan

obj = [
  { key: "name", value: "jack" },
  { key: "age", value: 10 },
  { key: "country", value: "india" },
  { key: "state", value: "Delhi" },
];

const res = {};
obj.forEach(({ key, value }) => Object.assign(res, { [key]: value }));

console.log(res);

Alternatively, use Object.fromEntries and map

obj = [
  { key: "name", value: "jack" },
  { key: "age", value: 10 },
  { key: "country", value: "india" },
  { key: "state", value: "Delhi" },
];

const res = Object.fromEntries(obj.map(Object.values));

console.log(res);
Siva K V
  • 10,561
  • 2
  • 16
  • 29
1

var obj=[{key: "name", value: "jack"},{key: "age", value: 10},{key: "country", value: "india"},{key: "state", value: "Delhi"}]
    
var myObj={};
for (var item of obj){
    myObj[item.key]=item.value
} 
console.log(myObj)

will output

{name: "jack", age: 10, country: "india", state: "Delhi"}
Zortext
  • 566
  • 8
  • 21
1

You can use reduce for this:

var input = [
    {key: "name", value: "jack"},
    {key: "age", value: 10},
    {key: "country", value: "India"},
    {key: "state", value: "Delhi"},
]
var output = input.reduce((r,{key,value}) => ({[key]:value,...r}),{})
console.log(output)

Output

{ state: 'Delhi', country: 'India', age: 10, name: 'jack' }

The solution uses

Jan Stránský
  • 1,671
  • 1
  • 11
  • 15
0

I think you want like this...

var obj = [
{key: "name", value: "jack"},
{key: "age", value: 10},
{key: "country", value: "india"},
{key: "state", value: "Delhi"}
];
let tempObject = {};

for (let c of obj) {
   tempObject[c.key]= c.value;
}

console.log(tempObject);
Rohit Tagadiya
  • 3,373
  • 1
  • 25
  • 25