簡體   English   中英

查找字符串中的子字符串並將其放入數組中

[英]Find the substrings in a string and put them in an array

所以我有這個字符串(添加換行符):

var str = '[{"id":1,"type":"one","status":"pending","user_id":2},
            {"id":2,"type":"two","status":"pending","user_id":14},
            {"id":3,"type":"three","status":"queue","user_id":5},
            {"id":4,"type":"four","status":"queue","user_id":8 }]';

我可以使用哪種算法在一個數組中獲取所有類型的值? 因此結果將是"one", "two", "three", "four"

您可以將字符串解析為對象,然后使用.map()創建所有類型值的數組

 var str = '[{"id":1,"type":"one","status":"pending","user_id":2},{"id":2,"type":"two","status":"pending","user_id":14},{"id":3,"type":"three","status":"queue","user_id":5},{"id":4,"type":"four","status":"queue","user_id":8 }]'; var array = JSON.parse(str); var myarray = array.map(function(item) { return item.type; }); console.log(myarray); 

var obj = JSON.parse(str);
var types = [];
for (var i in obj) {
    types.push(obj[i].type);
}

那應該為您提供所需的類型,並將其放入types數組中。

如果您正在編寫ES6,請遵循@ArunPJohny:

array.map(elt => elt.type)

要么

[ for (elt of array) elt.type ]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM