Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

How to dynamically calculate the fields in array of objects for a particular name filed in JavaScript

My code works fine to calculate various perks for towns. But I want to dynamically calculate other fields values as well.

var obj = [{
  "Town": "Newton",
  "PropertyType": "Multi Family",
  "InvestmentType": "Homeownership",
  "Perks": "Retail Store"
}, {
  "Town": "South Surrey",
  "PropertyType": "Multi Family",
  "InvestmentType": "Investment Property",
  "Perks": "Retail Store"
}, {
  "Town": "South Surrey",
  "PropertyType": "Multi Family",
  "InvestmentType": "Investment Property",
  "Perks": "Bus Station"
}, {
  "Town": "South Surrey",
  "PropertyType": "Condo",
  "InvestmentType": "Homeownership",
  "Perks": "Retail Store"
}];

var result = Object.values(obj.reduce(
  (a, { Town, Perks }) => { a[Town] = a[Town] || { Town, perks: {} };
  a[Town].perks[Perks] = (a[Town].perks[Perks] || 0) + 1;
  return a;
}, {}));

console.log(result);
question from:https://stackoverflow.com/questions/65862050/how-to-dynamically-calculate-the-fields-in-array-of-objects-for-a-particular-nam

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

On each iteration destructure the object, and get the Town, and the rest of properties. Get the entries of the other properties, and iterate it with Array.forEach(). As you did for Town create the object for the property key and value as needed, and increment the count.

const obj=[{"Town":"Newton","PropertyType":"Multi Family","InvestmentType":"Homeownership","Perks":"Retail Store"}, {"Town":"South Surrey","PropertyType":"Multi Family","InvestmentType":"Investment Property","Perks":"Retail Store"}, {"Town":"South Surrey","PropertyType":"Multi Family","InvestmentType":"Investment Property","Perks":"Bus Station"}, {"Town":"South Surrey","PropertyType":"Condo","InvestmentType":"Homeownership","Perks":"Retail Store"}];

const result = Object.values(obj.reduce((a, { Town, ...rest }) => {
  a[Town] = a[Town] || { Town };
  
  Object.entries(rest)
    .forEach(([k, v]) => {
      a[Town][k] = a[Town][k] || {};
      
      a[Town][k][v] = (a[Town][k][v] || 0) + 1;
    });
  
  return a;
}, {}));

console.log(result);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...