Javascript create object with objects

Create a new object with existing objects javascript

Solution 1: You could take a more functional approach with the following: This uses the map method that is attributed with arrays to loop over each item of the array and return a new array of parsed objects. So you have an array of objects, consisting of and .

Creating new object from 2 existing objects

You can use Javascript’s built-in spread syntax to help you out.

If you’re playing around with arrays, minor changes should be made. Take a look at an example:

let identificationIDs = < "HolderID": "1A000714", "TempIssueID": "1A000700" >let extendedId = [ "1A000714", "1A000700" ] let newIdentificationIds = ; console.log(newIdentificationIds)

You can try these following ways.

var identificationIDs = [ < HolderID: "1A000714", TempIssueID: "1A000700", >, ]; // Using `Object.values` const result = identificationIDs.map((obj) => (< . obj, ExtendedID: Object.values(obj), >)); // Alternatively, use destructuring const result2 = identificationIDs.map((< HolderID, TempIssueID >) => (< HolderID, TempIssueID, ExtendedID: [HolderID, TempIssueID], >)); console.log(result); console.log(result2);

Add new element to an existing object, Use this: myFunction.bookName = ‘mybook’; myFunction.bookdesc = ‘new’;. Or, if you are using jQuery:

Create new object from value of another object in js

So you have an array of objects, consisting of type and label . You want to make a «composite object» using that array. First thing, you don’t want respone to be an array, you want it to be an object. Second, you want to name the key on respone to the value of item.label .

let fields = [,,]// Create an empty object let respone = <>// Iterate over the fields array, using each one to set the key and value // on our respone object. fields.forEach(item => < respone[item.label] = item.type>);// Let's see how it looks! console.log(respone);

Edit : Based on a comment, it doesn’t really make sense to use .map() — the purpose of that is to return a new array, usually of transformed data, based on the array values. In this case, it makes more sense to use Array.forEach(. ) , the code has been amended to this.

Well the error is how you’re trying to define key.

item.label this need to be changed to [item.label] as you want computed key (which needs to evaluated first and than used as key )

let fields = [,,]let respone = []fields.forEach(item => < respone.push() > ) console.log(respone)

what’s the difference between item.label and [item.label] ?

[item.label] will resolve item.label first and than use as key and it need not to be a valid identifier
Читайте также:  Python tkinter масштабирование элементов

item.label try to use it directly as key which is not correct JS identifier in this case

If you want to transform the array into another array with the same number of elements, then you want map :

let fields = [,,] let response = fields.map(field => ()); console.log(response); 

The return from map is an array so you don’t need to create and push to separate storage; map does that for you.

If you want to create a new object with members based on the array content, reduce is what you want:

let fields = [,,] let response = fields.reduce((obj, field) => (), <>); console.log(response); 

(If you don’t mind the eslint warning, you can not create the temp objects during the reduce 🙂

let fields = [,,] let response = fields.reduce((obj, field) => < obj[field.label] = ''; return obj; >, <>); console.log(response); 

Adding elements to object, Just use a new element object for each element you’re adding, which is what you’ve done in the scope of a for-loop. – Konstantin Dinev. May 13, 2020 at 13:38.

How to create new object by two objects in javascript

You can write a function and get desired properties:

var obj1 = < start: "16:01", end: "23:59", totalqty: 1065, totalamount: 8229170 >var obj2 = < qty: 10, amt: 120 >const merge = (obj1, obj2) => < return < time: obj1.start + '-' + obj1.end, val: obj2.qty, totalqty: obj1.totalqty, totalamount: obj1.totalamount, price: obj2.amt >; > console.log(merge(obj1, obj2));

In addition, you can use spread syntax, but it merges all properties:

let obj1 = < start: "16:01", end: "23:59", totalqty: 1065, totalamount: 8229170 >let obj2 = < qty: 10, amt: 120 >let merged = ; console.log(merged );

or try to use Object.assign() and it is also merges all properties:

var obj1 = < start: "16:01", end: "23:59", totalqty: 1065, totalamount: 8229170 >var obj2 = < qty: 10, amt: 120 >var result = Object.assign(<>, obj1, obj2); console.log(result);

Read more Object.assign() here.

You could destructure the objects, rename some properties and return a new object.

const merge = (< start, end, totalqty, totalamount >, < qty: val, amt: price >) => (< time: start + "-" + end, val, totalqty, totalamount, price>), obj1 = < start: "16:01", end: "23:59", totalqty: 1065, totalamount: 8229170 >, obj2 = < qty: 10, amt: 120 >; console.log(merge(obj1, obj2));

JavaScript Array of Objects Tutorial, Creating an array of objects · Add a new object at the start — Array.unshift · Add a new object at the end — Array.push · Add a new object in the

How do I create a new object from an existing object in Javascript?

You could take a more functional approach with the following:

var parsed = content.items.map(function (item) < return < id: item.id, title: item.summary, start: item.start.dateTime, description: item.start.dateTime >>) 

This uses the map method that is attributed with arrays to loop over each item of the array and return a new array of parsed objects.

Читайте также:  '.htmlspecialchars($this->params['rtitle']).'

Take a look at this fuller example.

I have another way to convert this content. Using Underscore.js to make the code more readable. Here is the example:

var content = < "items": [< "id": "02egnc0eo7qk53e9nh7igq6d48", "summary": "Learn to code", "start": < "dateTime": "2017-03-04T19:00:00+05:30" >>, < "id": "nj4h567r617n4vd4kq98qfjrek", "summary": "Modern Data Architectures for Business Insights at Scale Confirmation", "start": < "dateTime": "2017-03-07T11:30:00+05:30" >>] >; var result = _.map(content.items, function(item) < return < id: item.id, title: item.summary, start: item.start.dateTime, description: "" >; >); console.log(result);

At the core, you are trying to ‘map’ from one set of data to another. Javascript’s mapping function of array should be sufficient. Eg.

var content = < "items": [< "id": "02egnc0eo7qk53e9nh7igq6d48", "summary": "Learn to code", "start": < "dateTime": "2017-03-04T19:00:00+05:30" >>] >; var results = content.items.map(function (item) < return < id: item.id, title: item.summary, start: item.start.dateTime, description: "" >; >); console.log(results); 

How To Use Object Methods in JavaScript, The Object.create() method is used to create a new object and link it to the prototype of an existing object. We can create a job object

Источник

JavaScript: Ways to Create New Objects from Old Objects

As a web developer, you are very likely to find yourself in need of creating new objects from old ones in Javascript when either developing complex projects or just writing some code for small applications. Although the job seems simple at first, there are many pitfalls and it is easy to write the wrong code that leads to disastrous outcomes if you do not understand your Javascript objects deeply.

In this article, we’ll walk through a couple of different ways to create a truly new object from a given object in Javascript.

Using Object.assign()

The Object.assign() method allows you to properly clone a given object by copying its properties to a new object. To use it, you pass the existing object to the Object.assign() method as the first argument. Then you can specify any additional properties you want to add to the new object as additional arguments.

This approach works with both shallow objects and deeply nested objects. Let’s have a look at a quick example:

// slingacademy.com var oldObject = < name: 'John', age: 35, skills: ['html', 'css', 'js'], contact: < email: '[email protected]', phone: 123 >, >; var newObject = Object.assign(<>, oldObject, < job: 'developer' >); console.log('old object:', oldObject); console.log('new object:', newObject);
old object: < name: 'John', age: 35, skills: [ 'html', 'css', 'js' ], contact: < email: '[email protected]', phone: 123 > > new object: < name: 'John', age: 35, skills: [ 'html', 'css', 'js' ], contact: < email: '[email protected]', phone: 123 >, job: 'developer' >

This code would create a new object called newObject that contains all the properties of the oldObject , plus the additional job property. The advantage of using the Object.assign() method is that it’s relatively simple and straightforward.

Читайте также:  Apache php localhost port

Using the Spread Operator

The spread operator is a relatively new addition to the language since ES6 and it allows you to quickly and easily create new objects from existing ones. To use it, you simply pass the existing object to the spread operator as the argument, and then you can add any additional properties you want to the new object.

// slingacademy.com var oldProduct = < name: 'Laptop', price: 50000, brand: 'Dell', description: < weight: '1.6kg', screen: 15.6, color: 'silver'>, >; // clone the object without adding new properties var newProduct1 = < . oldProduct >; console.log('newProduct1', newProduct1); // clone the object and add new properties var newProduct2 = < . oldProduct, freeShip: true >; console.log('newProduct2', newProduct2);
newProduct1 < name: 'Laptop', price: 50000, brand: 'Dell', description: < weight: '1.6kg', screen: 15.6, color: 'silver' >> newProduct2 < name: 'Laptop', price: 50000, brand: 'Dell', description: < weight: '1.6kg', screen: 15.6, color: 'silver' >, freeShip: true >

This code would create 2 new objects called newProduct1 (identical to the source object) and newProduct2 (contain all the properties of the old object plus the additional freeShip property).

As you can see, the code is short and concise.

Using JSON Trick

This is a classic trick to clone a Javascript object correctly and is still widely used today because of its reliability in all environments, from Node.js to browsers, and from legacy to modern browsers. We have 2 steps:

  1. Generate JSON string from the old object with JSON.stringify()
  2. Use JSON.parse() to produce the new object
// slingacademy.com var oldObject = < name: 'John Doe', age: 35, childArray: ['red', 'blue', 'yellow'], childObject: < 'location': 'USA', 'state': 'CA' >, >; var json = JSON.stringify(oldObject); var newObject = JSON.parse(json); // add new property to the cloned object newObject.newProperty = 'new property'; console.log(newObject);

Conclusion

Creating a new object from an existing object in Javascript can be a tricky task but it’s unavoidable and you will have to deal with it sooner or later. In this article, we’ve covered different ways of doing so. We’ve looked at the Object.assign() method, the spread operator, and the JSON old-school trick. There are still other techniques, but these are the three best and most popular.

Happy coding and have a nice day!

Источник

Оцените статью