![](/img/trans.png)
[英]How to get Array from Array String in JavaScript or AngularJS?
[英]how to get string from array using angularjs or javascript
var array = [
{id: 1, text: "one"},
{id: 2, text: "two"},
{id: 3, text: "three"},
{id: 4, text: "four"},
{id: 5, text: "five"}
];
var name = array.find(function(item){
return item.id == $localStorage.id;
});
返回我{id:2,文本:“ two”}期望兩個僅字符串沒有其他內容
您可以先查找對象,然后通過檢查find()
操作是否實際上返回了一個對象或undefined
對象來獲取text
屬性。
var array = [{ id: 1, text: "one" }, { id: 2, text: "two" }, { id: 3, text: "three" }, { id: 4, text: "four" }, { id: 5, text: "five" } ]; var findObj = array.find(function(item) { return item.id == 2; }); //check if findObj is defined or not var name = findObj? findObj.text: null; console.log(name);
如果您確定該localStorage值存在對象,則也可以使用解構直接從find()
獲取該text
值。 否則,將引發錯誤。
var array = [{ id: 1, text: "one" }, { id: 2, text: "two" }, { id: 3, text: "three" }, { id: 4, text: "four" }, { id: 5, text: "five" } ]; var {text} = array.find(function(item) { return item.id == 2; }); console.log(text);
您應該檢索找到的對象的屬性文本:
var object = array.find(function(item){
return item.id === $localStorage.id;
});
var name = object.text;
您所做的返回位於item.id == $localStorage.id
的位置的元素。 如果要獲取文本,則在以var name
返回元素之后,只需執行name.text
因為array.find()
返回通過邏輯運算的元素。
如果您喜歡使用es6語法,則可以這樣編寫。 您所做的一切都很好,除了需要獲得特定的對象值。
const array = [
{ id: 1, text: "one" },
{ id: 2, text: "two" },
{ id: 3, text: "three" },
{ id: 4, text: "four" },
{ id: 5, text: "five" }
];
// So here i use same find as you did.
let object = array.find(item => {
return item.id == $localStorage.id;
});
// And assigning text property of object to variable 'name'
// since object, can be undefined, using OR empty object,
// so no error will be thrown if so.
let { text: name } = object || {};
console.log(name);
來自https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/find :
find()方法返回滿足提供的測試功能的數組中第一個元素的值。 否則返回undefined。
嘗試以這種方式在使用id
查找時獲取text
屬性值
var array = [{ id: 1, text: "one" }, { id: 2, text: "two" }, { id: 3, text: "three" }, { id: 4, text: "four" }, { id: 5, text: "five" } ]; var name = array.find(function(item) { return item.id == 2; }).text; console.log(name);
find將返回滿足條件的對象
var object = array.find(function(item) {
return item.id == $localStorage.id;
});
var name = object? object.text: null;
console.log(name);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.