This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
Closed 3 years ago.
I have an array like this: [1, 2, 3, 4, 5] and I want to obtain from it an object like this:
[
{ product_id: 1 },
{ product_id: 2 },
{ product_id: 3 },
{ product_id: 4 },
{ product_id: 5 }
]
What is an ES6ish way to obtain this?
Problem is in understanding how ES6 .map() return works.
Add round brackets to map, because you want to return that statement. Curly brackets just opens body with no return value. (you have to add it on your own e.g. { return {product_id: item }})
const inputArr = [1, 2, 3, 4, 5];
const newArr = inputArr.map(item => ({ product_id: item }));
console.log('arrayLog', newArr);
Related
This question already has answers here:
Convert JS object to JSON string
(23 answers)
Closed 1 year ago.
I'm trying to convert a form data object to JSON
var dataFormItin = $("#formitinerary").serializeArray();
result
itinerary: {
'itinerary[0][date]': undefined,
'itinerary[0][title]': 'Day 1 to Colombo',
'itinerary[0][destinationId]': '5ff3b8d7f0f3bf04b8141362',
'itinerary[0][program]': 'asd',
'itinerary[0][transfer_duration]': '2 hours'
}
and i want to make it like
itinerary : [
{ date : ..., title :...},
{ date : ..., title :...}
]
Maybe, it will be solved your problem
// 1. Example Data
const serializeArray = [
{ name: "itinerary[0][date]", value: "" },
{ name: "itinerary[0][title]", value: "Day 1 to Colombo" },
{ name: "itinerary[0][destinationId]", value: "5ff3b8d7f0f3bf04b8141362" },
{ name: "itinerary[0][program]", value: "asd" },
{ name: "itinerary[1][date]", value: "" },
{ name: "itinerary[1][title]", value: "Day 1 to Colombo" },
{ name: "itinerary[1][destinationId]", value: "5ff3b8d7f0f3bf04b8141362" },
{ name: "itinerary[1][program]", value: "asd" },
]
// 2. Define object key here
const arrayOfKey = ['date', 'title', 'destinationId', 'program']
// 3. Create empty array object
const arrayObject = []
// 4. Transform Serialize Array into Array Object
for(i = 0; i < serializeArray.length / arrayOfKey.length; i++ ){
const newObject = {}
for(const key of arrayOfKey){
newObject[key] = (serializeArray.find(data => data.name == `itinerary[${i}][${key}]`)).value
}
arrayObject.push(newObject)
}
// 5. Show the result
console.log(arrayObject)
/**
* [
{
date: '',
title: 'Day 1 to Colombo',
destinationId: '5ff3b8d7f0f3bf04b8141362',
program: 'asd'
},
{
date: '',
title: 'Day 1 to Colombo',
destinationId: '5ff3b8d7f0f3bf04b8141362',
program: 'asd'
}
]
*/
Just needing to understand better use of new for loops in ES5/ES6.
I've read somewhere about the code above to modify the items array of objects.
var selected = [1, 2, 4, 6],
items = [
{ id: 1, selected: false },
{ id: 2, selected: false },
{ id: 3, selected: false },
{ id: 4, selected: false },
{ id: 5, selected: true },
{ id: 6, selected: false }
]
set = new Set(selected)
items.forEach(a => a.selected = set.has(a.id))
My question is, what is the for of loop equivalent of the forEach statement above?
for(let [index, value] of items.entries()) {
return value.selected = set.has(value.id)
}
What you have posted is very close-- the only problem I see is that you attempt to return, which will exit the entire function (and thus loop) prematurely. This is because the loop isn't calling any new function on each iteration, so the return leaves the function in which the for begins iterating. If you remove the return from your initial attempt, it functions correctly and as expected.
var selected = [1, 2, 4, 6],
items = [
{ id: 1, selected: false },
{ id: 2, selected: false },
{ id: 3, selected: false },
{ id: 4, selected: false },
{ id: 5, selected: true },
{ id: 6, selected: false }
]
set = new Set(selected)
// items.forEach(a => a.selected = set.has(a.id))
for(let [index, value] of items.entries()) {
value.selected = set.has(value.id)
}
console.log(items);
i want to just add an element to a list somewhere in my immutable object tree.
This question appears to have been answered here :
Append value to List
But for some reason it does not work for me.
If I have the following code :
var myState = {
a: {
b: {
c: [
{name: 'hi', value: 2},
{name: 'howdy', value: 3}
]
}
}
}
myState = Immutable.fromJS(myState);
myState = myState.update(['a', 'b', 'c'], function (myList) {
myList.push({"name": "hallo", "value": 4})
}
);
I get an error :
Uncaught TypeError: Cannot read property 'push' of undefined
which indicates that the myList parameter being passed into the callback is null.
Why is this happening?
fiddle:
https://codepen.io/owatkins/pen/brMava
This is how it should be written:
myState.updateIn(['a', 'b', 'c'], function (myList) {
return myList.push({"name": "hallo", "value": 4})
}
);
Below is a working example:
var myState = Immutable.fromJS({
a: {
b: {
c: [{
name: 'hi',
value: 2
},
{
name: 'howdy',
value: 3
}
]
}
}
})
myState = myState.updateIn(['a', 'b', 'c'], function(myList) {
return myList.push({
"name": "hallo",
"value": 4
})
});
console.info('myState = ' + myState.toJS())
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.min.js"></script>
notice that I'm using updateIn instead of update and returning the result of push
After much stuffing around, the only solution I could come up with is to get the array, and convert to JS, push an element onto it, then convert it back to an immutable... and then use setIn, NOT updateIn, and NOT update.
var myState = {
a: {
b: {
c: [
{name: 'hi', value: 2},
{name: 'howdy', value: 3}
]
}
}
}
myState = Immutable.fromJS(myState);
var list = myState.getIn(['a', 'b', 'c'])
var list = list.toJS();
list.push({"name": "hallo", "value": 4});
var v = Immutable.fromJS(list)
myState = myState.setIn(['a', 'b', 'c'], v)
This looks like a horrible solution, but it is the only thing that works for me so far.
Usually it takes about 5 minutes to learn how to add an element to a list in a framework or language.
I wasn't expecting it to take 5 HOURS.
The documentation for this framework is an absolute disgrace.
Here is the data:
var data1 = [{
"Date": "2016-07-09",
"H1_PNL2": 20,
"H1_NAV2" : 20
"H2_PNL2": 20,
"H2_NAV2" : 20,
"NAV": 26.28,
"PNL": 7.61
}, {
"Date": "2016-07-10",
"H1_PNL2": 20,
"H1_NAV2" : 20
"H2_PNL2": 20,
"H2_NAV2" : 20,
"NAV": 27.55,
"PNL": 12.89
}];
If I only want to select Date and H2_PNL2 i.e
var data1 = [{
"Date": "2016-07-09",
"H2_PNL2": 20,
}, {
"Date": "2016-07-10",
"H2_PNL2": 20,
}];
How to select the specific properties I want?
Use Array.prototype.map to iterate through your array, then for each object construct a new object with just the properties that interest you:
data1.map(o => ({ Date: o.Date, H2_PNL2: o.H2_PNL2 }));
EDIT: Deleting properties can go two ways, depending on if you want to preserve the original or not.
Destructive:
data1.forEach(o => { delete o.NAV; delete o.PNL; });
Non-destructive:
data1.map(o => {
var c = Object.assign({}, o);
delete c.NAV; delete c.PNL;
return c;
});
I'm trying to build a tree using JSON for which i'm trying to just print in browser console.
var json = [{
name: "1",
id: 1,
child: [{
name: "11",
id: 11,
child: [{
name: "111",
id: 111
}, {
name: "112",
id: 112
}]
}, {
name: "12",
id: 12
}]
}];
function ya(obj) {
console.log(obj.name);
if (obj.child) {
console.log("length=" + obj.child.length);
for (i = 0; i < obj.child.length; i++) {
ya(obj.child[i]);
}
}
}
ya(JSON.parse(JSON.stringify(json))[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here I would like to print
1
11
111
112
12
in console. But it only prints
1
11
111
112
I want to do this recursively. How can I achieve this?
You need to declare i with var:
for (var i = 0; i < obj.child.length; i++)
See Difference between variable declaration syntaxes in Javascript (including global variables)? for more details.