最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mapping Object to convert object to array - Stack Overflow

programmeradmin0浏览0评论

I have this function here:

var obj = {
  name: 'Holly',
  age: 35,
  role: 'producer'
};


function convertObjectToList(obj) {
 return Object.keys(obj).map(k => [k, obj[k]]);
}
convertObjectToList(obj);

This function converts an array to obj. So if I have that obj above i'll get something like this:

[['name', 'Holly'], ['age', 35], ['role', 'producer']]

Now I want to focus here:

return Object.keys(obj).map(k => [k, obj[k]]);

Breaking it down, Object.keys basically returns an array of a given object's own enumerable properties and map iterates in an array and so something with it. I am trying to understand the arrow function above and try to break it down into simpler understandable code for me.

function convertObjectToList(obj) {
 Object.keys(obj).map(function(key){
     obj = [key, obj[key]];
 });
  console.log(obj);
}

But this one did not work. Instead it only returns ["role", undefined].

Is there anyone out there who can make me understand in laymans term and break down the code so I would understand it clearly.

Sorry I am beginner. Noob.

I have this function here:

var obj = {
  name: 'Holly',
  age: 35,
  role: 'producer'
};


function convertObjectToList(obj) {
 return Object.keys(obj).map(k => [k, obj[k]]);
}
convertObjectToList(obj);

This function converts an array to obj. So if I have that obj above i'll get something like this:

[['name', 'Holly'], ['age', 35], ['role', 'producer']]

Now I want to focus here:

return Object.keys(obj).map(k => [k, obj[k]]);

Breaking it down, Object.keys basically returns an array of a given object's own enumerable properties and map iterates in an array and so something with it. I am trying to understand the arrow function above and try to break it down into simpler understandable code for me.

function convertObjectToList(obj) {
 Object.keys(obj).map(function(key){
     obj = [key, obj[key]];
 });
  console.log(obj);
}

But this one did not work. Instead it only returns ["role", undefined].

Is there anyone out there who can make me understand in laymans term and break down the code so I would understand it clearly.

Sorry I am beginner. Noob.

Share Improve this question asked Jun 18, 2017 at 13:35 user7435957user7435957 1
  • it needs return statement, The arrow function k => [k, obj[k]] is equivalent to function(k){ return [k, obj[k]] } – user93 Commented Jun 18, 2017 at 13:37
Add a ment  | 

6 Answers 6

Reset to default 5

Arrow functions are like functions, but with a different syntax. Normal functions use the syntax

function(x, y){
    return x + y;
}

Arrow functions use the one-line syntax

(x, y) => x + y

or the multi-line syntax

(x, y) => {
    return x + y;
}

In your example,

return Object.keys(obj).map(k => [k, obj[k]]);

translates to

return Object.keys(obj).map(function(k) {
    return [k, obj[k]];
});

since the function takes one parameter k (before the arrow) and returns [k, obj[i]] (after the arrow).

This is your second function:

function convertObjectToList(obj) {
  Object.keys(obj).map(function(key){
   obj = [key, obj[key]];
  });
  console.log(obj);
}

There are a few things that is out of place here:

  1. Your second function does not have a return value. So function call convertObjectToList will return undefined.
  2. You are reassigning the value of obj with an array [key, obj[key]], which is not what you want to do. That is why you are getting ['role' , undefined], because the last key of obj is role, and since obj has been modified to an array an not an object, obj['role'] will return undefined.
  3. You need a return value inside the map, otherwise each element in the returned array will be undefined.

So the correct code would be the following:

var obj = {
  name: 'Holly',
  age: 35,
  role: 'producer'
};

function convertObjectToList(obj) {
 return Object.keys(obj).map(function(key){
   let currElement = [key, obj[key]];
   return currElement
 });
}

var res = convertObjectToList(obj);

console.log(res);

It should be so

var obj = {
	name: 'Holly',
	age: 35,
	role: 'producer'
};


function convertObjectToList(obj) {

	return Object.keys(obj).map(function (k) {
		return [k, obj[k]];
	})
}
convertObjectToList(obj);

When using arrow function you could avoid the return statement if the arrow function contains only one line. So when using regular function you need to return manually

var obj = {
  name: 'Holly',
  age: 35,
  role: 'producer'
};

function convertObjectToList(obj) {
  return Object.keys(obj).map(function(k) {
    return [k, obj[k]]
  });
}

var result = convertObjectToList(obj);
console.log(result);

Object.keys returns an array which elements are strings corresponding to the enumerable properties found directly in obj. The order of properties is the same as that given by manually cycling on the properties of the object.

    var arr = ["a", "b", "c"];
alert(Object.keys(arr)); // chiama alert con argomento "0,1,2"

// array like object
var obj = { 0 : "a", 1 : "b", 2 : "c"};
alert(Object.keys(obj)); // chiama alert con argomento "0,1,2"

Assuming you are passing your object , the map is built likethis, that's your result.

function objToStrMap(obj) {
    const strMap = new Map();
    for (const k of Object.keys(obj)) {
        strMap.set(k, obj[k]);
    }
    return strMap;
}

In your code try this change

function convertObjectToList(obj) {
 Object.keys(obj).map(function(key){
     return [key, obj[key]];  //obj = [key, obj[key]];
 });

}

You need to understand how the map function works to see what you did wrong. The map function takes a callback function which we would refer to as The Mapper. This function accepts each item in the array, does some manipulation on it, and returns the result of the manipulation. The map function itself loops over the array, and passes a single item each time to the mapper, and then adds the result to a NEW array.

Here is an implementation of the map function using a good old for loop:

function customMap(array, mapper) {
  var result = [];
  for (int i = 0; i < array.length; i++) {
    var temp = mapper(array[i]);
    result.push(temp);
  }
  return result;
}

Now we can pare this implementation to your function, and see what you did wrong:

  1. Your mapper function did not return anything. Therefore, in the implementation above, the value of temp would be undefined, and would be pushed as such to the result array.
  2. You tried to apply the mapper to the entire obj object, instead of each item in the keys array. By doing so, you change the value of obj variable, and therefore lost its content after the first iteration.
  3. Your convertObjectToList itself did no return anything, so there's nothing to display at the end.

To fix this, you can use the following:

var obj = {
  name: 'Holly',
  age: 35,
  role: 'producer'
};


function convertObjectToList(obj) {
 return Object.keys(obj).map(function(key) {
   var temp = [key, obj[key]];
   console.log('current item: ', temp);
   return temp;
 });
}

var result = convertObjectToList(obj);
console.log('final result: ', result);

And finally, there's no need to apologize for being a noob - we all start as such.

发布评论

评论列表(0)

  1. 暂无评论