如何遍历特定的对象属性

时间:2015-06-13 12:53:43

标签: javascript jquery

我想减少代码中的IF语句数量:

http://jsfiddle.net/b0ftLujj/

重复太多属性,这是一个问题。

可能与上述代码有关的第二部分。 我想迭代我的对象属性:

myObject ={ property_1: myValue_1, property_2: myValue_2, otherProperty_1: myValue_1 };

基于上面的一个对象,我想只通过property_1, property_2进行迭代,忽略otherProperty_1

我的对象最多可以有5个“property_x”属性,或者根本没有属性。我试图制作一个if语句,就像这个伪代码:

for(var statName in myObject){
  If(myObject has any property called : 'property_1, property_2, property_3, property_4, property_5'.indexOf(statName) != -1;)
    //Then display in html: '<img src="images/' + property_x(where x is a property 1/2/3/4 or 5) and it would display only available properties in current object. I can make it work with an 5x if else statements to check for every property, since there cannot be property_1 and property_3/4/5 if "2" is missing. I was looking for a better way to display it.
  }
}

使用JavaScript的答案是最好的,但jQuery也是一个选项 欢迎使用我可以用来了解更多材料的任何链接。

由于

2 个答案:

答案 0 :(得分:1)

我不确定您是否理解了问题的第二部分,但这是fiddle的简化版本:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace InsertUpdateDeleteDataGridView
{
    public partial class Form1 : Form
    {
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\bj\documents\visual studio 2013\Projects\InsertUpdateDeleteDataGridView\InsertUpdateDeleteDataGridView\Information.mdf;Integrated Security=True");
        SqlCommand cmd;
        SqlDataAdapter adapt;
        //ID variable used in Updating and Deleting Record
        int id = 0;




        public Form1()
        {
            InitializeComponent();
            //invok fn
            DisplayData();
        }

        private void btninsert_Click(object sender, EventArgs e)
        {
           if(txtbxname.Text!="" && txtbxcountry.Text!="")
          {
            cmd = new SqlCommand("INSERT INTO users(name,country) VALUES(@name,@country)",con);
            con.Open();
            cmd.Parameters.AddWithValue("@name", txtbxname.Text);
            cmd.Parameters.AddWithValue("@country", txtbxcountry.Text);
            cmd.ExecuteNonQuery();
            con.Close();
            MessageBox.Show("record added succesfully","Success");
            DisplayData();
            ClearData();
           }
            else
             {
            MessageBox.Show("please provide Details!","Error");
             }

        }
           //displaying Data in DataGridView

        private void DisplayData()
        {
          con.Open();
            //creating obj of datatable method
            DataTable dt= new DataTable();
            dt = null;
            adapt.Fill(dt);
            dataGridView1.DataSource=dt;
            con.Close();
        }
        //clearing datat
        private void ClearData()
        {
            txtbxname.Text="";
            txtbxcountry.Text="";
            id=0;
        }

        private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
          id=Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
            txtbxname.Text=dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
            txtbxcountry.Text=dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
        }
         //update record
        private void btnupdate_Click(object sender, EventArgs e) 
        {  
            if(txtbxname.Text!="" && txtbxcountry.Text!="")
            {

            cmd=new SqlCommand("UPDATE users SET name=@name,state=@state WHERE id=@id ",con);
            con.Open();
            cmd.Parameters.AddWithValue("@id",id);
            cmd.Parameters.AddWithValue("@name",txtbxname.Text);
            cmd.Parameters.AddWithValue("@country",txtbxcountry.Text);
            cmd.ExecuteNonQuery();
            MessageBox.Show("record updated succesfully","success");
            con.Close();
                DisplayData();
            ClearData();
           }
            else
            {
             MessageBox.Show("please select the record to update!","erorrr!!");
            }
         }
        //deleterecord
        private void btndelete_Click(object sender, EventArgs e)
        { 
              if(txtbxname.Text!="" && txtbxcountry.Text!="")
            {
            cmd=new SqlCommand("DELETE students WHERE id=@id",con);
            con.Open();
            cmd.Parameters.AddWithValue("@id",id);
            cmd.ExecuteNonQuery();
            con.Close();
            MessageBox.Show("record deleted successfully!");
            DisplayData();
            ClearData();

        }
        else
        {
            MessageBox.Show("please select record to delete","error");
         }


     }
   }

 }

答案 1 :(得分:1)

我不确定我是否完全理解,但你的伪代码实际上非常有效:-)。您可以使用for prop in obj语句遍历每个对象属性(您还应该检查它是否是对象自己的属性),并使用obj[prop]代码获取此属性的值。

for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        html += '<img src="' + obj[prop] + '" />';
    }
}

这是http://jsfiddle.net/b0ftLujj/1/

的小提琴