迭代jSON数组并将值转换为百分比 [英] Iterate a jSON array and convert the values to percentage

查看:30
本文介绍了迭代jSON数组并将值转换为百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json数组.

I have a json array .

{1:2500,2:3000,3:3000,4:2500,5:5000,6:3000}

{1: 2500, 2: 3000, 3: 3000, 4: 2500, 5: 5000, 6: 3000}

此处的最大值为5000,为100%.

Here 5000 is the maximum value and it is 100%.

我想迭代此数组并形成另一个javascript数组{50%,60%,60%,50%,100%,60%}

I want to iterate this array and form another javascript array {50%, 60%, 60%, 50%, 100%, 60%}

如何使用javascript有效地做到这一点?

How can i do this efficiently in javascript?

推荐答案

好吧,这些实际上不是数组.在JS中,数组有方括号,对象(如您所拥有的)有花括号.当您看到以下内容: {name:"dave",age:"30"} 时,这是 name age 的对象是属性.数组在JS中不能具有属性.因此,数组可能看起来像这样: ["dave",32] .同样,您不能将数字作为属性.

Well, these are actually not arrays. In JS, arrays have square brackets and objects (like what you have) have curly braces. When you see something like this: {name: "dave", age: "30"}, this is an object whereby name and age are properties. Arrays can't have properties in JS. So an array might look like this: ["dave", 32]. Also, you can't have numbers as properties.

var x = {1:2500}//无法正常工作

所需的最终输出在描述对象时(使用curly时)也将不起作用,并且您想要的是数组.因此,您可能想要的更像是将数组 [2500,3000,3000,2500,5000,3000] 转换为看起来像 ["50%","60%," 60%," 50%," 100%," 60%]

the final output that you want will also not work as you described an object (when you used the curlies) and what you'll want is an array. So what you'll probably want is more like converting an array [2500, 3000, 3000, 2500, 5000, 3000] to an array that looks like ["50%", "60%", "60%", "50%", "100%", "60%"]

请注意,在第一个数组中,值是真数字(不在引号中),但最终结果数组中的值将是字符串,因为我们有百分号

Notice that in the first array, the values were true numbers (not in quotes) but the end result array the values will be strings since we have the percent sign

您可以使用地图功能执行此操作.此代码将数组的每个项目映射"到一个函数.函数返回的任何内容都将替换原始数组中的原始项

You can use a map function to do this. This code "maps" each item of an array to a function. Whatever the function returns will replace the original item in the original array

var originalArray = [3000, 5000];
var newArray = originalArray.map(function(item) {
  return ((item / 5000) * 100) + '%'
})

console.log(newArray)

这篇关于迭代jSON数组并将值转换为百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆