我有一个json:
items = "[
{"prop1":"here","prop2":"all","contentType":"All","dateRangeType":"Anytime","prop3b":"here"},
{"prop1":"pole","prop2":"all","contentType":"All","dateRangeType":"Anytime","excludeWords":"there ","excludeDomains":"asteroid","prop3b":"pole"},
{"prop1":"orcsstar","prop2":"all","contentType":"All","dateRangeType":"Anytime","excludeWords":"","excludeDomains":"dwarves","prop3b":"orcsstar"},
{"prop1":"guntham","prop2":"all","contentType":"All","dateRangeType":"Anytime","excludeWords":"","prop3b":"gunther"},
{"prop1":"depot","prop2":"all","contentType":"All","dateRangeType":"Anytime","excludeWords":"","prop3b":"depot"},
{"prop1":"department","prop2":"all","contentType":"All","dateRangeType":"Anytime","excludeWords":"dept","prop3b":"depart"}
]"
所以我在这里有6个条目存储在var项目中。 我如何才能获得4个条目。 我尝试过切片,但它在“{}”括号上并没有很好地分开。或[],在开始时出现,请帮助我选择{}。中包含的4个条目的子数组。
答案 0 :(得分:1)
一旦你纠正外部引号
,切片就可以了
items = '[{"prop1":"here","prop2":"all","contentType":"All","dateRangeType":"Anytime","prop3b":"here"},{"prop1":"pole","prop2":"all","contentType":"All","dateRangeType":"Anytime","excludeWords":"there","excludeDomains":"asteroid","prop3b":"pole"},{"prop1":"orcsstar","prop2":"all","contentType":"All","dateRangeType":"Anytime","excludeWords":"","excludeDomains":"dwarves","prop3b":"orcsstar"},{"prop1":"guntham","prop2":"all","contentType":"All","dateRangeType":"Anytime","excludeWords":"","prop3b":"gunther"},{"prop1":"depot","prop2":"all","contentType":"All","dateRangeType":"Anytime","excludeWords":"","prop3b":"depot"},{"prop1":"department","prop2":"all","contentType":"All","dateRangeType":"Anytime","excludeWords":"dept","prop3b":"depart"}]'
var parsedAndSlicedAndStringified = JSON.stringify(JSON.parse(items).slice(0,4), null, 4);
document.getElementById('pre').innerHTML = parsedAndSlicedAndStringified ;;

<pre id="pre">
&#13;
答案 1 :(得分:0)
这应该保留为对象JSON.parse(items)
而不是字符串,并使用像Underscore这样的库在对象中搜索您想要的项目,或只是.slice(0,3)
来获取第一个4.如果需要返回字符串JSON.stringify()
上面的结果。
完整JS中的前4项:
JSON.stringify(JSON.parse(items).slice(0,3))