从数组内部更新对象属性

时间:2020-08-04 03:13:34

标签: javascript arrays json object

我知道这都是基本知识,但这对我来说是新的,所以任何帮助都会很棒。我正在尝试制作一个更新对象属性的函数,其中所有对象都在数组内部。这是我要参加的训练营的作业,这是我到目前为止所获得的。我知道返回值必须在循环范围之外,但是我更迷恋于条件语句以及访问和操作数组内部对象键的正确表示法。

function findObject(array, key, target) {
  //look through the array by creating a for loop

  for (let i = 0; i < array.length; i++) {

    //set conditional to check if an object in array has target value on its key prop

    if (array[i].key === target) {

      //if the above condition is met, return that object
      return array[i];
    }

  } //if its not return null
  return null;
}

提示:3。实现功能findObject。 其参数为:

一个称为数组的数组
数组充满对象
一个称为键的字符串
一个字符串称为target

浏览数组并返回其键属性具有目标值的对象

如果未找到目标,则返回null

1 个答案:

答案 0 :(得分:0)

似乎键是一个字符串,其值是您要搜索的属性/键的名称。请检查以下代码是否适用。

function findObject(array, key, target) {
let foundObj=null;
  //look through the array by creating a for loop

  for (let i = 0; i < array.length; i++) {

    //set conditional to check if an object in array has target value on its key prop

    if (array[i][key] === target) {

      //if the above condition is met, return that object
      foundObj=array[i];
      break;
    }

  } //if its not return null
  return foundObj;
}
console.log(findObject([{name:"usa",id:"usa"},{name:"uk",id:"uk"}],"name","usa"));