3

So, I had the very tiny, but hard for me task from my last interview. I just itreseted in how to solve it. I think that we need to implement the recursion in this task, but I do not know it clearly.

The task:

let arr = [{name: 'width', value: 300}, {name: 'height', value: 100}];

On output we must have:

let obj = {width:300, height: 100};

The count of array objects can be infinity.

P.S. I'll be pleased if you provide me with link on knowleges to how make this task done.

Thank you.

1
  • OP, my answer below keeps height/width paired like you wanted for each object. Let me know if you need more help with that. Have you tried any other answers here yet? Commented Apr 13, 2018 at 18:46

9 Answers 9

5

An alternative using the function reduce

Brief explanation

  • The function Array.prototype.reduce loops an array applying a handler for each object.
  • The accumulator a will contain the result from each iteration.
  • The function converter receives the accumulator and the current object.
  • This Object.assign(a, {[name]: value}) assigns a new property to the current accumulator.
  • Computed property names {[name]: value} that code will build an object as follow:
{ width: 300 }

let arr = [{name: 'width', value: 300},{name: 'height', value: 100}],
    converter = (a, {name, value}) => (Object.assign(a, {[name]: value})),
    obj = arr.reduce(converter, {});

console.log(obj);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script>

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

9 Comments

Good code, but doesn't this make it so width and height would be on their own? I believe OP wants width and height paired, so it's two objects from original array being combined. So that original array length should be double the length of final output. I believe OPs desired output is one object with height and width PER PAIR in the original array.
@Nerdi.org the answer follows the OP's requirements.
But that's what I'm getting at... OP has an array of unlimited objects. The expected outcome is that pairs of width/height dimensions (from 2 objects in original array) are grouped together in a single object. Those are the requirements, and as far as I can tell most of the answers here completely disregard that he wants values paired together, not listed as individual objects. If I'm misunderstanding how your code accomplishes that, I apologize - I'm just trying to clarify because there's a lot of answers here that simply don't result in the outcome OP wants.
But if I misunderstood it, I apologize. OP never stated really whether he's pairing height/width or if he wants every possible array name/value to be in a single object.
@Nerdi.org but, the input is an array. The OP only wants to build a big Object with the nested objects from that array.
|
3

The array .reduce method would be a good fit. Start with an empty object and for each array item, add an entry to the object with that key and value. Example:

let arr = [{name: 'width', value: 300}, {name: 'height', value: 100}];

let result = arr.reduce((combo, item) => {
    combo[item.name] = item.value;
    return combo;
}, {});

console.log(result);

Comments

1

First, you're missing a comma between your two objects in the array :)

Whenever you're looking to process an array and come up with a single value, you're looking to use array.reduce. You can choose the direction (reduce or reduceRight) and the accumulator function, to produce the value (or object) desired.

Comments

1

Another way using reduce, destructurization and object spread operator:

const src = [{
  name: 'width',
  value: 300
}, {
  name: 'height',
  value: 100
}]

const reducer = (acc, { name, value }) => ({
  ...acc,
  ...{ [name]: value }
});


const out = src.reduce(reducer, {});

console.log(out);

Comments

0

You can create the object by adding the key value pairs in the array, with the help of the bracket notations :

let arr = [{name: 'width', value: 300},{name: 'height', value: 100}];
 let obj = {};
 arr.forEach(pair => obj[pair.name] = pair.value)
 console.log(obj);

Comments

0

You can use forEach() to solve it as well.

let arr = [{name: 'width', value: 300},{name: 'height', value: 100}];
let obj = {};
arr.forEach(val=>obj[val.name]=val.value);

1 Comment

for() would be faster though.
0

You can use Array.map() to create an array of objects in the form of { [name]: value }, and merge them to a single object by spreading into Object.assign():

const arr = [{name: 'width', value: 300}, {name: 'height', value: 100}];

const object = Object.assign(...arr.map(({ name, value }) => ({ [name]: value })));

console.log(object);

Comments

0
var len = arr.length, 

var newA = []; 
let width, height, item; 
for(var x = 0; x < len; x+=2){ //add 2 for pair loop because width/height in diff array objects 
 item.width = arr[x].value;
 item.height = arr[x+1].value; 
 newA.push(item); 
 // newA = [{width:value, height:value}, {width:value, height:value}];
}
console.log(newA);

This should work for grouping width and height together in your final array :)

If you want just one big object (make sure there are no name duplicates !)...

var len = arr.length, 
obj = {}; 
for(var x = 0; x < len; x++){ 
 obj[arr[x].name] = arr[x].value;
} 
console.log(obj);

Comments

-1

You can solve this with just a for loop:

var obj = {};
for (var i=0; i<arr.length; i++){
    obj[arr[i].name] = arr[i].value;
}

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.