Dominando Object.assign en JavaScript

Object.assign en JavaScript: fusiona y clona objetos, explica copias superficiales y límites, con ejemplos prácticos y guía para copias profundas.

8 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Dominando Object.assign en JavaScript

Los objetos son una herramienta muy potente en JavaScript y muchas veces necesitamos copiar valores de un objeto a otro o fusionar varios objetos. Para eso sirve Object.assign, un método incorporado que copia propiedades de uno o varios objetos origen a un objeto destino.

Qué es Object.assign

Object.assign es un método nativo que toma un objeto target y uno o varios sources y copia las propiedades enumerables propias de los sources al target. Sintaxis simple: Object.assign(target, ...sources)

Ejemplo 1 copiar simple

const user = { name: Ali }; const extra = { age: 25 }; const result = Object.assign({}, user, extra); console.log(result) // { name: Ali, age: 25 }

En este caso usamos un objeto vacío como destino para fusionar user y extra sin mutar los originales.

Ejemplo 2 sobrescribir propiedades

Si la misma propiedad existe en varios objetos, el que aparece más a la derecha sobrescribe a los anteriores. Ejemplo: const obj1 = { skill: React }; const obj2 = { skill: Node.js }; const merged = Object.assign({}, obj1, obj2); console.log(merged) // { skill: Node.js }

Ejemplo 3 clonar un objeto (shallow copy)

Object.assign puede usarse para crear una copia superficial: const original = { city: Lahore }; const clone = Object.assign({}, original); console.log(clone) // { city: Lahore } console.log(original === clone) // false

La copia es superficial, por lo que si hay objetos anidados sus referencias se mantienen.

Ejemplo 4 múltiples fuentes

const a = { x: 1 }; const b = { y: 2 }; const c = { z: 3 }; const all = Object.assign({}, a, b, c); console.log(all) // { x: 1, y: 2, z: 3 }

Limitaciones

Object.assign realiza copias superficiales. Para copias profundas use structuredClone o librerías como Lodash. Además no copia propiedades no enumerables ni símbolos de forma predeterminada.

Usos frecuentes

Merge de objetos, creación de copias superficiales y establecimiento de valores por defecto son usos comunes de Object.assign en desarrollo moderno.

Sobre Q2BSTUDIO

En Q2BSTUDIO somos una empresa de desarrollo de software y aplicaciones a medida especializada en soluciones modernas como inteligencia artificial, ciberseguridad, servicios cloud aws y azure y servicios de inteligencia de negocio. Diseñamos software a medida y aplicaciones a medida orientadas a resultados, implementando agentes IA y soluciones de ia para empresas que integran Power BI y analítica avanzada. Si buscas desarrollo de aplicaciones y software a medida conoce nuestros trabajos en desarrollo de aplicaciones y software a medida y si te interesa potenciar tus procesos con inteligencia artificial visita nuestra oferta de servicios de inteligencia artificial. También ofrecemos auditorías y pentesting para reforzar la ciberseguridad de tus sistemas, migraciones y gestión de cloud y proyectos de servicios inteligencia de negocio con Power BI para convertir datos en decisiones.

Reflexión final

Object.assign es una herramienta sencilla pero poderosa para trabajar con objetos en JavaScript. Ten en cuenta sus límites y combínala con otras técnicas según necesites clones profundos o manejo avanzado de propiedades. Si quieres llevar tus proyectos al siguiente nivel con software a medida, automatización o IA, en Q2BSTUDIO te ayudamos a diseñar la solución adecuada.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat