如何通过其属性之一检索数组中的对象?

时间:2018-11-22 12:10:33

标签: javascript object

在Javascript中,如何通过其属性之一检索数组中的对象?

大家好, 假设我们具有以下内容:

   "Attributes":[
       {
           "Name":"Brief",
           "Value":"This skirt was fabriced from ...."
       },
       {
           "Name":"Details",
           "Value":"Measurements and Pictures are real"
       },
       {
           "Name":"SKUNumber",
           "Value":"12345678"
       }
   ]

我需要做的是基于“名称”获取“值”的值。

例如:

console.log(Attributes.Brief)   ==> "This skirt was fabriced from ...."

所以我需要一个函数来帮助实现

请注意,我不想使用对象的索引,因为它的顺序可能会更改。

谢谢

4 个答案:

答案 0 :(得分:2)

好吧,总是展示自己尝试过的事情,而不是仅仅问问。.

您可以使用Array.find来实现

let Attributes = [
                     {
                        "Name":"Brief",
                        "Value":"This skirt was fabriced from ...."
                     },
                     {
                        "Name":"Details",
                        "Value":"Measurements and Pictures are real"
                     },
                     {
                        "Name":"SKUNumber",
                        "Value":"12345678"
                     }
                  ]
                  
function getValueByName(name) {
  return Attributes.find(d => d.Name.toLowerCase() == name.toLowerCase()).Value
}

console.log(getValueByName('Brief'))
console.log(getValueByName('details'))
console.log(getValueByName('SKUNumber'))

答案 1 :(得分:1)

您可以选择使用Array.prototype.filter

const d = [{
    "Name": "Brief",
    "Value": "This skirt was fabriced from ...."
  },
  {
    "Name": "Details",
    "Value": "Measurements and Pictures are real"
  },
  {
    "Name": "SKUNumber",
    "Value": "12345678"
  }
]

console.log(d.filter(x=>x.Name==="Brief")[0].Value)

您还可以使其更通用:

const d = [{
    "Name": "Brief",
    "Value": "This skirt was fabriced from ...."
  },
  {
    "Name": "Details",
    "Value": "Measurements and Pictures are real"
  },
  {
    "Name": "SKUNumber",
    "Value": "12345678"
  }
]

const getValOfXfromArrByValOfY = (arr, x, y, val) => arr.find(z => z[y] === val)[x]

console.log(getValOfXfromArrByValOfY(d, 'Value', 'Name', 'SKUNumber'))

答案 2 :(得分:1)

您可以将Proxy与带有getter的键一起使用,这将返回带有值的对象的查找。

var object = { attributes: [{ Name: "Brief", Value: "This skirt was fabriced from ...." }, { Name: "Details", Value: "Measurements and Pictures are real" }, { Name: "SKUNumber", Value: "12345678" }] },
    attributes = new Proxy(
        object.attributes,
        { get: (array, prop) => (array.find(({ Name }) => Name === prop) || {}).Value }
    );
   
console.log(attributes.Brief);
console.log(attributes.SKUNumber);

答案 3 :(得分:0)

您可以使用javascript查找功能,请参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find,请参见下面的示例代码:

rails script/generate model Book