繁体   English   中英

如何使用angularjs或javascript从数组获取字符串

[英]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()返回通过逻辑运算的元素。

您可以使用filtermap 这样,您可以按照自己的方式自定义过滤结果。

 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.filter(a=> a.id === 2).map(b=> {return b.text}); console.log(name) 

如果您喜欢使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM