gpt4 book ai didi

javascript - 使用 jquery 或 javascript 从 json 变量数据获取值

转载 作者:行者123 更新时间:2023-12-01 04:04:45 25 4
gpt4 key购买 nike

json 输出类似于:{"苹果":3,"另一个":1,"更多":5,"沃尔沃":1,"奥迪":1,"福特":1}

我需要对每个收到的值进行附加。它们旁边的数字是它们存在的次数。

我知道它可能是带有“foreach”值的东西,但是,由于 json 响应的值和键是可变的,所以我很难弄清楚如何做到这一点。

我希望附加顺序取决于数字有多大。如果它更大,则将其打印在顶部,依此类推...

例如:

<div id="values">
<p>The value "more" is repeated 5 time(s).</p>
<p>The value "apple" is repeated 3 time(s).</p>
<p>The value "another" is repeated 1 time(s).</p>
...
</div>

记住! react 可以改变, react 不会总是苹果、另一个、更多、沃尔沃、奥迪和福特......它可以改变!

编辑:我可以用这个做一些事情,但是,我如何以更高或更低的值对它们进行排序?

for (var key in interests) {
if (interests.hasOwnProperty(key)) {
console.log(key + " -> " + interests[key]);
}
}

编辑:

var data = {"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1}; // initial data
var interestsValue = []; // data with values

for (var key in data){ interestsValue.push({ name: key, value: data[key] }); } // send data with values
interestsValue.sort(function(a, b){ return b.value - a.value; }); // sort values

console.log(interestsValue); // values ordered from bigger to smaller

最佳答案

首先 - 将对象转换为有效数组:

var data = {"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1};
var arr = [];

for (var key in data)
{
arr.push({ name: key, value: data[key] });
}

然后...使用该数组与 jQuery、Angular 等...来填充您的元素

享受吧:)

关于javascript - 使用 jquery 或 javascript 从 json 变量数据获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41920149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com