根据数组项对象属性值查找数组的索引值

时间:2017-07-17 21:11:17

标签: javascript arrays object

我这里有这个数组( stressValues ):

[ { angeredoutsidecontrol: 1 }, { difficultiespileup: 2 } ]

我想基于其中一个包含对象的属性名称找到数组索引值,例如 angeredoutsidecontrol ,它将返回 0

我怎样才能做到这一点?

这是我到目前为止所做的:

for(const value of values) {
  const stressValue = Object.values(value)[0];
  const valueName = Object.keys(value)[0];

  for (const name in stressValues) {
    if (name === valueName) {
      console.log(name);
      console.log(values.indexOf(name)); // trying to get it to return 0
    }
  }
}

2 个答案:

答案 0 :(得分:2)

 OnClickListener(View view){
    //use the same instance of mediaplayer and call mp.start();
    if(isPlaying){
       mp.pause();
    }else{
    mp.start();
 }
}

答案 1 :(得分:2)

如果对象始终只有一个属性,则可以将Object.keysfindIndex一起使用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace double_generator
{
class Program
{
    static void Main()
    {
        try
        {
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\xexex\Desktop\green.txt"))
            {
                double number = 0.009999999999999999999999999999;

                do
                {
                    number += 0.000000000000000000000000000001;
                    file.WriteLine(number.ToString("N30"));
                } while (number <= 0.099999999999999999999999999999);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}

编辑:如果您想要更通用的解决方案,可以使用includes,因此我们会检查对象是否在其键中包含指定的对象:

var stressValues = [ { angeredoutsidecontrol: 1 }, { difficultiespileup: 2 } ];

var angerIndex = stressValues.findIndex((value) => Object.keys(value)[0] === 'angeredoutsidecontrol');
console.log(angerIndex);

相关问题