Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
62 views
in Technique[技术] by (71.8m points)

javascript - change json dynamically from parameters

I want to create a json object according to function parameters but it takes the parameters as a string.

userSchema.statics.updated = async function (_id, field, value) { // it does not take that params
  const user = await this.updateOne({ _id }, { $set: { field: value } }); //!!!!
};

The field parameters is a json field that i create like name,age... But it always create and object like

{"field":value}

how can i fix it?

Json structure example:

{
        "email": "",
        "password": "",
        "surname": "",
        "name": "",
        "nickname": "",
        "birthdate": ""
    }
question from:https://stackoverflow.com/questions/65645586/change-json-dynamically-from-parameters

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are passing the string "field" as the value field, Try pass a real field name, for example:

const jsonFile = require('jsonFile');
const object = JSON.parse(jsonFile);
fieldName = 'email';
userSchema.statics.updated(_id, object[fieldName], false));

// You can also:

const keys = Object.keys(object);
userSchema.statics.updated(_id, object[keys[0]], false));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...