我知道以前也有人问过类似的问题,但这个问题有点不同。我有一个未命名对象的数组,其中包含一个命名对象的数组,我需要得到其中“name”为“string 1”的对象。下面是一个示例数组。

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

更新:我应该早点说,但一旦我找到它,我想用一个编辑过的对象替换它。


当前回答

这个答案适用于typescript / Angular 2,4,5 +

我在上面@rujmah的回答的帮助下得到了这个答案。他的回答带来了数组计数……然后查找该值并用另一个值替换它…

这个答案所做的只是抓取可能通过另一个模块/组件在另一个变量中设置的数组名…在这种情况下,我构建的数组有一个css名称stay-dates。它所做的就是提取这个名称然后允许我将它设置为另一个变量,像这样使用它。在我的例子中,它是一个html css类。

let obj = this.highlightDays。Find (x => x.css); let index = this.highlightDays.indexOf(obj); Console.log('这里我们看到highlightdays是什么',obj.css); let dayCss = obj.css;

其他回答

你可以循环数组并测试该属性: 函数搜索(nameKey, myArray){ For(令i=0;i < myArray.length;我+ +){ if (myArray[i].name === nameKey) { 返回myArray[我]; } } } Const数组= [ {name:"string 1", value:"this", other: "that"}, {name:"string 2", value:"this", other: "that"} ]; const resultObject = search("string 1",数组); console.log (resultObject)

根据ECMAScript 6,您可以使用findIndex函数。

array[array.findIndex(x => x.name == 'string 1')]

如果使用jQuery,请尝试$.grep()。

http://api.jquery.com/jquery.grep/

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

var foundValue = array.filter(obj=>obj.name==='string 1');

console.log(foundValue);

一行回答。 你可以使用过滤函数来得到结果。

Var数组= [ {name:"string 1", value:"this", other: "that"}, {name:"string 2", value:"this", other: "that"} ]; Console.log (array.filter(function(arr){return arr.name == 'string 1'})[0]);