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

javascript - Object.entries with forEach to map array of objects returns undefined except when console.log is used - Stack Overf

programmeradmin7浏览0评论

I have an array of objects that have key value pairs, I want to find a specific key in each object and return the value.

A sample of the Array:

filterCounties=[
  {
    "StateName": "Delaware",
    "CountyName": "Kent",
    "FIPS": 10001,
    "Eligibles_2017": 33292,
    "Eligibles_2018": 34938,
    "Penetration_2017": 0.107,
    "Penetration_2018": 0.123
  },
  {
    "StateName": "Delaware",
    "CountyName": "New Castle",
    "FIPS": 10003,
    "Eligibles_2017": 94030,
    "Eligibles_2018": 98080,
    "Penetration_2017": 0.128,
    "Penetration_2018": 0.164
  },
  {
    "StateName": "Delaware",
    "CountyName": "Sussex",
    "FIPS": 10005,
    "Eligibles_2017": 61964,
    "Eligibles_2018": 65990,
    "Penetration_2017": 0.082,
    "Penetration_2018": 0.097
  },
  {
    "StateName": "Delaware",
    "CountyName": "Pending County Designation",
    "FIPS": 10,
    "Eligibles_2017": 9,
    "Eligibles_2018": 0,
    "Penetration_2017": 0,
    "Penetration_2018": 0
  }
]

The key I am looking for is Penetration_2018 - I can use the following code and output the values using console.log

const mapTest = new Map(
      Object.entries(filterCounties).forEach(([key, value]) =>
        console.log((key, value["Penetration_2018"]))
      )
    );

This will output the values: console.log output

However if I assign to a variable and then log the variable

 const mapTest = new Map(
      Object.entries(filterCounties).forEach(
        ([key, value]) => (key, value["Penetration_2018"])
      )
    );
    console.log(`This is mapTest ${mapTest}`);

I get [object Map] with no values - I thought that when using an arrow function, return was implicit?

Image of output - with or without String concatenation enter image description here

I ultimately want to extract these values to assign them to the Y axis of a Victory BarChart. Thanks for any insight / guidance.

I have an array of objects that have key value pairs, I want to find a specific key in each object and return the value.

A sample of the Array:

filterCounties=[
  {
    "StateName": "Delaware",
    "CountyName": "Kent",
    "FIPS": 10001,
    "Eligibles_2017": 33292,
    "Eligibles_2018": 34938,
    "Penetration_2017": 0.107,
    "Penetration_2018": 0.123
  },
  {
    "StateName": "Delaware",
    "CountyName": "New Castle",
    "FIPS": 10003,
    "Eligibles_2017": 94030,
    "Eligibles_2018": 98080,
    "Penetration_2017": 0.128,
    "Penetration_2018": 0.164
  },
  {
    "StateName": "Delaware",
    "CountyName": "Sussex",
    "FIPS": 10005,
    "Eligibles_2017": 61964,
    "Eligibles_2018": 65990,
    "Penetration_2017": 0.082,
    "Penetration_2018": 0.097
  },
  {
    "StateName": "Delaware",
    "CountyName": "Pending County Designation",
    "FIPS": 10,
    "Eligibles_2017": 9,
    "Eligibles_2018": 0,
    "Penetration_2017": 0,
    "Penetration_2018": 0
  }
]

The key I am looking for is Penetration_2018 - I can use the following code and output the values using console.log

const mapTest = new Map(
      Object.entries(filterCounties).forEach(([key, value]) =>
        console.log((key, value["Penetration_2018"]))
      )
    );

This will output the values: console.log output

However if I assign to a variable and then log the variable

 const mapTest = new Map(
      Object.entries(filterCounties).forEach(
        ([key, value]) => (key, value["Penetration_2018"])
      )
    );
    console.log(`This is mapTest ${mapTest}`);

I get [object Map] with no values - I thought that when using an arrow function, return was implicit?

Image of output - with or without String concatenation enter image description here

I ultimately want to extract these values to assign them to the Y axis of a Victory BarChart. Thanks for any insight / guidance.

Share Improve this question edited Feb 12, 2018 at 13:25 Ashley W asked Feb 12, 2018 at 13:18 Ashley WAshley W 1031 gold badge2 silver badges7 bronze badges 3
  • Thanks for such a quick response - I had tried that with the same result - just tried again - will edit the post to show an image of output. – Ashley W Commented Feb 12, 2018 at 13:24
  • 1 forEach() never provides a return, unless you consider undefined a return. Use map() it always provides a return. – zer00ne Commented Feb 12, 2018 at 13:24
  • See javascript - Why is .forEach returning undefined? - Stack Overflow instead if you want to return the object after mutating the elements of the original object. – user202729 Commented Jan 12, 2021 at 9:48
Add a ment  | 

3 Answers 3

Reset to default 9

Several issues:

  • forEach always returns undefined. You need to use map instead.
  • (key, value["Penetration_2018"]) is not a tuple, but a ma operator expression and results in the value of value["Penetration_2018"]. Use square bracket notation instead.
  • A Map has no useful representation when cast to string. You need to turn it to an array or something else to get a more useful string representation:

Code:

const mapTest = new Map(
    Object.entries(filterCounties).map(
        ([key, value]) => [key, value["Penetration_2018"]]
    )
);
console.log(`This is mapTest ${JSON.stringify([...mapTest])}`);

With arrays it is more conventional to just apply map directly on the array, and it is a mystery why you would need a Map anyway. If you want the unique values, then use a Set:

const uniques = [...new Set(filterCounties.map(value => value["Penetration_2018"]))];
console.log(`This is uniques: ${uniques}`);

Object.entries is pretty useless on an array. If necessary, you'd use the array entries method.

I thought that when using an arrow function, return was implicit?

An arrow function with a concise body implicitly returns the expression value, yes. However, in your first example, console.log does not return anything, and in both examples, forEach returns nothing. And in your second example, you use the ma operator for some kind of "tuple" notation while the Map constructor requires arrays.

Instead of trying to use "forEach to map array of objects", you should use the map method to map an array of objects!

const mapTest = new Map(filterCounties.map((value, key) => [key, value.Penetration_2018]));
console.log('This is mapTest:', mapTest);

.forEach does not return a value or an array. Try using .map instead. Also, you don't need a Javascript Map in this case (it can't have repeated keys), considering furthermore that Victory BarChart seems to take an Array as data (not a Map).

This is my suggested change:

const mapTest = filterCounties.map(
  element => ({'Penetration_2018': element['Penetration_2018']})
)

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论