Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

228
Views
¿Cómo fusionar objetos?

Por ejemplo, de estos dos objetos:

 var object1 = { "color": "yellow", "size": null, "age": 7, "weight": null } var object2 = { "color": "blue", "size": 51, "age": null }

Quiero esto ( object2 anula object1 excepto por propiedades null o propiedades que no tiene):

 { "color": "blue", "size": 51, "age": 7, "weight": null }
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Dupdo

 var src = { name: 'Apple', price: 5}; var dst= angular.copy(src);
  • copia profunda

extender :

 var mergedObject = angular.extend(dst, src1, src2, ...)
  • copia superficial

Fusionar :

 var mergedObject = angular.merge(dst, src);
  • desde angular 1.4+
  • copia profunda (recursiva)

Si no desea sobrescribir con nulo, puede usar este .


Objeto.assign() :

 let movie2 = Object.assign({}, movie1, { episode: 8 });
  • para Angular 2+ (ECMAScript 6)

Fuentes:

  • https://docs.angularjs.org/api/ng/function

  • http://davidcai.github.io/blog/posts/copy-vs-extend-vs-merge/

over 4 years ago · Santiago Trujillo Report

0

Para versiones más nuevas (al menos 1.4.0) de angular, puede usar angular.merge

A diferencia de extend(), merge() desciende recursivamente a las propiedades de los objetos de origen, realizando una copia profunda.

over 4 years ago · Santiago Trujillo Report

0

Usar anualr.extend no producirá el resultado solicitado. El valor nulo de object2.age anulará el valor de object1.age.

angular.extend(objeto1, objeto2) producirá el siguiente resultado:

 { "color" : "blue", "size" : 51, "age" : null, <=== undesirable result "weight" : null }

Use el siguiente código para omitir las propiedades nulas

 for (var prop in object1) { if(object1.hasOwnProperty(prop) && object2.hasOwnProperty(prop) && object2[prop]!=null) { object1[prop] = object2[prop]; } }

Esto producirá el siguiente resultado solicitado

 { "color" : "blue", "size" : 51, "age" : 7, "weight" : null }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!