json输出有点像:
{"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1}
我需要对每个收到的值进行追加。它们旁边的数字是它们存在的次数。
我知道它可能会出现“for each”值,但是,由于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>
记住!响应可以改变,响应不会总是苹果,另一个,更多,沃尔沃,奥迪和福特...它可以改变!
编辑: 我可以用这个做点什么,但是,我如何用更高或更低的价值订购呢?
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
答案 0 :(得分:1)
首先 - 将对象转换为有效数组:
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等的数组来填充你的元素
享受:)
答案 1 :(得分:1)
像这样。使用jquery的$.each
方法浏览你的objcet然后用append
方法将html附加到你的div中。
var obj= {"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1};
text = "";
$.each(obj,function(index,element){
text +=" <p>The value " +index+ " is repeated "+ element + " time(s).</p>";
});
$("#values").append(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="values">
</div>
JS小提琴https://jsfiddle.net/uobedcf0/
参见 更新 小提琴:
答案 2 :(得分:0)
如上所述,首先将对象转换为数组。
var data = {"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1};
function sortByValue (data){
var dataArray=[];
for(var key in data){
dataArray.push({name:key ,value :data[key]});
}
dataArray.sort(function(a,b){return b.value- a.value}); //sort it in descreasing order
return dataArray;
}
var text="";
var objArray = sortByValue(data);
$.each(objArray,function(index,object){
text +=" <p>The value " +object.name+ " is repeated "+ object.value + " time(s).</p>";
});
$("#values").append(text)