zoealonso
zoealonso

Reputation: 43

Add new object in JSON array

I'm working with javascript and JSON. I have a JSON object like this one:

{"firstName":"John", "lastName":"Doe", "id":"1"}

In my case, I have a function like this one:

function addNewValues(jsonArray, firstName, lastName, id)

In case the "firstName" is not a match, I should create a new value in the array.

From

addNewValues({"firstName":"John", "lastName":"Doe", "id":"1"}, "Jane", 
"Doe", "2"); 

it should return:

[
{"firstName":"John", "lastName":"Doe", "id":"1"},
{"firstName":"Jane", "lastName":"Doe", "id":"2"}
]

How can I add this new position? I tried myObj.push({"firstName":firstName, "lastName":lastName }); without any success.

Thanks in advance.

Upvotes: 4

Views: 933

Answers (8)

Abhishek Anand
Abhishek Anand

Reputation: 46

Everything is ok with your code except the line

    addNewValues({"firstName":"John", "lastName":"Doe", "id":"1"}, "Jane", "Doe", "2"); 

You are supposed to pass array of JSON (assuming that you have written the function already), but right now you are passing JSON object only .

Try this instead

    addNewValues([{"firstName":"John", "lastName":"Doe", "id":"1"}], "Jane", "Doe", "2"); 

once you do this , the below mentioned line will execute without any error.

    myObj.push({"firstName":firstName, "lastName":lastName }); 

You can also check this working demo in jsfiddle

Upvotes: 1

baao
baao

Reputation: 73211

To get that you can use below function. It will update the records if the firstname exists, or it will create a new entry in case it doesn't. Below function will find the first entry with given firstname.

let obj = {
    "firstName": "John",
    "lastName": "Doe",
    "id": "1"
};

function addNewValues(arr, firstName, lastName, id) {
    arr = Array.isArray(arr) ? arr : [arr];
    let obj = arr.find(v => v.firstName === firstName);
    if (! obj) {
        return arr.concat({firstName, lastName, id});
    }
    obj.lastName = lastName;
    obj.id = id;
    return arr;
}

console.log(addNewValues(obj, "Jane", "Foo", 3));

Upvotes: 1

cнŝdk
cнŝdk

Reputation: 32145

You can use .some() method to test if the given array doesn't contain an object with this firstName, then push a new object with these properties.

This is how should be your code:

function addNewValues(jsonArray, firstName, lastName, id){
     if(!jsonArray.some(function(obj){
         return obj.firstName === firstName;
      })){
          jsonArray.push({"firstName": firstName, "lastName" : lastName, "id": id});
      };
}

Demo:

var jsonArray = [{"firstName":"John", "lastName":"Doe", "id":"1"}];

function addNewValues(jsonArray, firstName, lastName, id){
     if(!jsonArray.some(function(obj){
         return obj.firstName === firstName;
      })){
          jsonArray.push({"firstName": firstName, "lastName" : lastName, "id": id});
      };
}

addNewValues(jsonArray, "Jane", 
"Doe", "2");

console.log(jsonArray);

Upvotes: 1

Yordan Nikolov
Yordan Nikolov

Reputation: 2678

If your json is a string, you have to parse it with JSON.parse and then put it into array if it not.

var array = [];

// with push
function addNewValues(firstName, lastname, id) {
  // check if firstName already exists
  if(array.filter(function(x) { return x.firstName===firstName; }).length===0) {
    array.push({
        'firstName': firstName,
        'lastName': lastname,
        'id': id
    });
  }
}

// with concat
// I would suggest you to use this method
function addNewValues1(arr, firstName, lastname, id) {
  if(arr.filter(function(x) { return x.firstName===firstName; }).length===0) {
    return arr.concat([{
        'firstName': firstName,
        'lastName': lastname,
        'id': id
    }]);
  }
  return arr;
}

addNewValues("Jahn", "Doe", "1");
addNewValues("Jane", "Doe", "2");
console.log(array);

// with concat
array = addNewValues1(array, "Foo", "Bar", "3");
console.log(addNewValues1(array, "Foo1", "Bar1", "4"));
console.log(array);

Upvotes: 2

gaback
gaback

Reputation: 638

newArray = [];
newArray.push(jsonArray);
function addNewValues(newArray, firstname, lastname, id){
    jsonArray.push({
        'firstName': firstname,
        'lastName': lastname,
        'id': id
    });
    return newArray;
}
newArray = addNewValues(newArray, 'Jane', 'Doe', '2');
// newArray now is array of 2 jsonObject

Hope this help.

Upvotes: -1

Shiladitya
Shiladitya

Reputation: 12181

Here you go with the solution https://jsfiddle.net/52q9v57j/

var jsonArray = [{"firstName":"John", "lastName":"Doe", "id":"1"}];

addNewValues = function(jsonArray, firstName, lastName, id){
	return jsonArray.push(
  	{"firstName": firstName, "lastName": lastName, "id": id}
  );
}

addNewValues(jsonArray, "Jane", "Doe", "2"); 
console.log(jsonArray);

Upvotes: 0

Nilesh Khisadiya
Nilesh Khisadiya

Reputation: 1658

Please see below code. Hope this will help to understand your problem. After adding new array, updated value showing in console.

You can read more about Javascript Array Methods: Unshift(), Shift(), Push(), And Pop()

var jsonArray=[{"firstName":"John", "lastName":"Doe", "id":"1"}];

function addNewValues(firstName, lastName, id){
// here you can check if exists or not
jsonArray.push({"firstName":firstName, "lastName":lastName,"id":id });
console.log(jsonArray);
return jsonArray;
}
<button type="button" onClick='addNewValues("Jane", 
"Doe", "2"); '>Click Me!</button>

Upvotes: 0

Alberto Trindade Tavares
Alberto Trindade Tavares

Reputation: 10356

In your call addNewValues, you should pass an array as the first parameter (you are passing an object instead):

var values = [{"firstName":"John", "lastName":"Doe", "id":"1"}];
addNewValues(values , "Jane", "Doe", "2"); 

Upvotes: 0

Related Questions