1

I have a javascript object that is DYNAMICALLY CREATED like this

[
  {"user":"James","errors":["signature must be signed!"]},
  {"user":"Jones","errors":["signature must be signed!"]}
]

I am trying to dynamically add a new error in errors array inside that object.

This is what i have tried:

validationErr.push({ "user" : "James", "errors" : ["start time musst be filled!"] });

But i get a new entry

[
  {"user":"James","errors":["signature must be signed!"]},
  {"user":"Jones","errors":["signature must be signed!"]},
  {"user" : "James", "errors" : ["start time musst be filled!"]}
]

instead of this

[
  {"user":"James","errors":["signature must be signed!", "start time musst be filled!"]},
  {"user":"Jones","errors":["signature must be signed!"]},
]

How can I add to existing array inside my object?

0

5 Answers 5

3

ES6 solution using Array#find, destructuring and Array#push

const data=[{user:"James",errors:["signature must be signed!"]},{user:"Jones",errors:["signature must be signed!"]}];

function addError(username, error){
   const {errors} = data.find(({user})=>user===username);
   if(errors){ errors.push(error) }
}

addError("James", "error occured");
console.log(data)

Sign up to request clarification or add additional context in comments.

2 Comments

what is return false; doing with Array#forEach?
@NinaScholz must have confused it with the jQuery each function.
2

You could iterate the array with Array#sort and find the right user. Then push error and exit the loop.

If no user is found, a new object is created with the errors array.

function addError(user, error) {
    if (!data.some(function (a) {
        if (a.user === user) {
            a.errors.push(error);
            return true;
        }
    })) {
        data.push({ user: user, errors: [error] });
    }
}

var data = [{ user: "James", errors: ["signature must be signed!"] }, { user: "Jones", errors: ["signature must be signed!"] }];

addError("James", "start time musst be filled!");
addError("foo", "bar");

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES6 with Array#find

function addError(user, error) {
    var object = data.find(a => a.user === user);
    if (object) {
        object.errors.push(error);
    } else {
        data.push({ user, errors: [error] });
    }
}

var data = [{ user: "James", errors: ["signature must be signed!"] }, { user: "Jones", errors: ["signature must be signed!"] }];

addError("James", "start time musst be filled!");
addError("foo", "bar");

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

2 Comments

Maybe i am making a mistake creating an object? What about Gaurav answer?
that is an answer to a different question.
2

A simple and effective approach to do it is:

validationErr[validationErr.map((e)=>e.user).indexOf('James')].errors.push("value");

or like this

validationErr[validationErr.findIndex(e => e.user === 'James')].errors.push("value");

This took 0.03 ms vs find() method approach which took 0.07 ms. 200% faster on an average!

Although, fastest method is to use key-value pair but you can't use this approach since your object is being dynamically generated

var ValidationErr = {};

ValidationErr['James'] = [];
ValidationErr['Robby'] = [];
ValidationErr['James'].push("Not Authenticated");
ValidationErr['James'].push("Wrong Credentials");
ValidationErr['Robby'].push("No Error");

console.log(ValidationErr['James']);

2 Comments

Who downvoted this? I want to hear more comments on this because i find this also a good solution!
@lewis4u I have revised my answer. Earlier, I didn't read the question carefully as I was in a hurry then. Hope it helps!
1

It is a bit ugly, but you can achieve what you'd like assuming you have unique users and errors field is never undefined;

function func(arr, idField, id, updField, upd) {
     arr.find(obj => obj[idField] == id)[updField].push(upd);
}

validationErr = [
  {"user":"James","errors":["signature must be signed!"]},
  {"user":"Jones","errors":["signature must be signed!"]}
];

func(validationErr, "user", "James", "errors", "start time must be filled!");

console.log(validationErr);

Using find() to get the first occurrence with correct user name, and push into its array, with one-liner.

4 Comments

@lewis4u yes, if user == James is unique, you'd get a single one in the array after filtering, so would need to fetch it with that selector.
what if my object is dynamically created?
@lewis4u You can still pass the fields as parameters, but the zero will stay assuming the filter condition will always result a single result. Updated my answer to have parametric field selects
@lewis4u Why do you think this is the best answer? It iterates the whole array even if the first element is the one you want. Using some or find as suggested by Nina would be much better as they stop the iteration as soon as possible.
1

You should push inside the object with that specific key.

Then your syntax must be;

validationErr[0].errors.push("start time musst be filled!");

Where validationErr[0] gives you object with james and push to his errors.

1 Comment

Hmm it is dynamically created so I think this would not be a good solution, because your solution is hardcoded!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.