-3

What I wanted to achieved is convert an array of object into an object.

mycode

 var arr = data.questions
        var obj = {};
        for (let i = 0; i < arr.length; i++) {
            obj[arr[i].key] = arr[i].value;
        }
        console.log(obj)

result

data 
(2) [{…}, {…}]
0: {id: 48, questionaire: 94, question: "Helloworld", input_answer: null, order: 0, …}
1: {id: 49, questionaire: 94, question: "sadasdas", input_answer: null, order: 1, …}
length: 2
__proto__: Array(0)

want to achieve

questions {id: 11, questionaire: 16, question: "what?", input_answer: null, order: 0, …}

2 Answers2

1

const input = [
    {id: 48, questionaire: 94, question: "Helloworld", input_answer: null, order: 0},
    {id: 49, questionaire: 94, question: "sadasdas", input_answer: null, order: 1}
];

const output = input.reduce((a, obj)=>{
    a[obj.id] = obj;
    return a;
}, {});

console.log(output);
// Or you can access the specific objects using there keys
console.log(output[48]);
console.log(output[49]);

If there is only one object in the array, then you can simply access the object using index.

var array = [{id: 44, questionaire: 90, question: "asd", input_answer: null, order: 0}];

console.log(array[0]);
random
  • 7,756
  • 3
  • 19
  • 25
  • @how about there are multiple objects in an array? –  Feb 18 '19 at 08:09
  • @JanMichaelDough - provide input and output you want. – random Feb 18 '19 at 08:20
  • data (2) [{…}, {…}] 0: {id: 48, questionaire: 94, question: "Helloworld", input_answer: null, order: 0, …} 1: {id: 49, questionaire: 94, question: "sadasdas", input_answer: null, order: 1, …} length: 2 __proto__: Array(0) –  Feb 18 '19 at 08:24
  • Where is the output? – random Feb 18 '19 at 08:27
  • here is that catch i want to seperate it as two objects –  Feb 18 '19 at 08:30
  • @JanMichaelDough - I am not really sure how you want actual result, I have updated my code, where I had created a single object with id as key and assigned the whole object to it and later you can access the specific objects using there id's. – random Feb 18 '19 at 08:37
0

You can use Object.assign()

var a = [{
  a: 1
}, {
  b: 2
}, {
  c: 3
}]
var obj = {};
a.forEach(e => {
  Object.assign(obj, e)
})
console.log(obj)
ellipsis
  • 12,049
  • 2
  • 17
  • 33