根据现有参数值将参数添加到json

时间:2015-07-29 09:54:10

标签: javascript jquery json

{
    "data": [{
        "prop": "prop1",
        "template": "template1",
        "group": [{
            "group_name": "Group 1",


        }, {
            "group_name": "Group 2",


        }, {
            "group_name": "Group 3",


        }]
    }]
}

在上面的json中,我需要根据group_no推送group_name。即如果group_name等于Group 1,则group_no等于10。并形成以下json。如何更新现有的json?

{
    "data": [{
        "prop": "prop1",
        "template": "template1",
        "group": [{
            "group_name": "Group 1",
            "group_no": "10"

        }, {
            "group_name": "Group 2",
            "group_no": "11"

        }, {
            "group_name": "Group 3",
            "group_no": "12"

        }]
    }]
}

2 个答案:

答案 0 :(得分:0)

不确定你的意思是不循环,因为无论如何你需要循环它。但你想要的是这样做的:

data[0].group = data[0].group.map(function(el) {
    switch (el.group_name) {
        case 'Group 1': return el.group_no = '10';
        case 'Group 2': return el.group_no = '11';
        ...
        default: return el;
    }
}); 

如果您的JSON对象实际上是文本,则首先使用var parsed = JSON.parse(data);并使用parsed而不是data。您可以data = JSON.stringify(parsed);

后跟

答案 1 :(得分:0)

这样做。



private static class ViewHolder {
    public final FrameLayout rootView;
    public final ImageView imHotelProfile;


    private ViewHolder(FrameLayout rootView, ImageView imHotelProfile) {
        this.rootView = rootView;
        this.imHotelProfile = imHotelProfile;

    }

    public static ViewHolder create(FrameLayout rootView) {
        ImageView imHotelProfile = (ImageView)rootView.findViewById( R.id.im_hotel_profile );
        ImageView imLike = (ImageView)rootView.findViewById( R.id.im_like );

        return new ViewHolder( rootView, imHotelProfile);
    }
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final ViewHolder vh;
    if ( convertView == null ) {
        View view = mInflater.inflate( R.layout.list_adapter, parent, false );
        vh = ViewHolder.create((FrameLayout) view);
        view.setTag( vh );
    } else {
        vh = (ViewHolder)convertView.getTag();
    }

    GsonObj item = getItem( position );

    // TODOBind your data to the views here
    // fill data

    return vh.rootView;
}

private LayoutInflater mInflater;

// Constructors
public ListAdapter(Context context, List<GsonObj> objects) {
    super(context, 0, objects);
    this.mInflater = LayoutInflater.from(context);
}
public ListAdapter(Context context, GsonObj[] objects) {
    super(context, 0, objects);
    this.mInflater = LayoutInflater.from(context);
}
&#13;
&#13;
&#13;