我有一个具有不同值的数组的对象
var myObj = {
"number": 10,
"general": "general",
"array": [{
"num1": 11,
"text": "text1",
}, {
"num2": 1,
"text": "text2",
}, {
"num3": 3,
"text": "text3",
} ]
};
如何获得像text1,text2,text3
这样的结果我试试这个
for (i=0; i <myObj.array.length; i++) {
a = myObj.array[i].text
a1 += a
}
答案 0 :(得分:6)
使用Array.prototype.map
方法
var result = myObj.array.map(function (item) {
return item.text;
});
如果您需要将结果作为字符串,则可以使用join
方法:
result.join(',');
答案 1 :(得分:3)
您可以将值推送到数组,然后加入join(',')
var myObj = {
"number": 10,
"general": "general",
"array": [{
"num1": 11,
"text": "text1",
}, {
"num2": 1,
"text": "text2",
}, {
"num3": 3,
"text": "text3",
}, ]
};
var a1 = [];
for (i=0; i <myObj.array.length; i++) {
a1.push(myObj.array[i].text);
}
var resultString = a1.join(',');
答案 2 :(得分:3)
var myObj = {
"number": 10,
"general": "general",
"array": [{
"num1": 11,
"text": "text1",
}, {
"num2": 1,
"text": "text2",
}, {
"num3": 3,
"text": "text3",
}]
};
var mapped = myObj.array.map(function(obj) {
return obj.text;
});
var joined = mapped.join(',');
console.log(joined);
答案 3 :(得分:1)
您可以使用forEach-Loop执行此操作:
myObj.array.forEach(function(entry) {
line += entry.text;
});