I have 2 arrays
var labels = ["DESKTOP","MOBILE","TABLET"]
var chartData = ["100","10","15"]
And I need to combine these into one array with objects
var myData = [{
label: DESKTOP,
value: 100},
{
label: MOBILE,
value: 10},
{
label: TABLET,
value: 15},
];
So far I've pushed labels into an array with new object
$.each(labels, function (index, item) {
myData.push({
label: item,
value: ''
});
});
I've done empty value, and now can't push value to an object in array. Just can't figure out how to push each value to new object in array. Help is much appreciated.
Thanks.
Data is sample only.
var labels = ["DESKTOP", "MOBILE", "TABLET"];
var chartData = ["100", "10", "15"];
var myData = [];
labels.forEach(function(e, i) {
myData.push({
label: e,
data: chartData[i]
})
})
document.write(JSON.stringify(myData));
How about:
$.each(labels, function (index, item) {
myData.push({
label: item,
value: chartData[index]
});
});
Related
I am trying to remove an object from an array but it I dont know what I am doing wrong.
I have this array declared:
listA: [
{ title: 'Food', value: 'Patato' },
{ title: 'Drink', value: 'Cola' },
{ title: 'Desert', value: 'Cheesecake' },
],
I am trying to remove the object where its value is 'Cola', what I have tried is this:
this.listA.filter(x => x.value !== 'Cola');
And it returns me the same list
I want to return this:
listA: [
{ title: 'Food', value: 'Patato' },
{ title: 'Desert', value: 'Cheesecake' },
],
Your code should be filtering just fine, I think the issue here is that filter does not modify the original array, it returns a new array with the filtered results. If you want it to overwrite the original array, you'll need to say this.listA = this.listA.filter(...)
const listA = [
{ title: "Food", value: "Patato" },
{ title: "Drink", value: "Cola" },
{ title: "Desert", value: "Cheesecake" },
];
const result = listA.filter((obj) => obj.value !== 'Cola');
Looks like you need to do something like
this.listA = this.listA.filter(x => x.value !== 'Cola')
The filter method is immutable hence the original array isn't changed
As a complement to https://stackoverflow.com/a/70688107/6316468, here is what filter does under the hood (the original array this remains untouched):
var xs = [1, 2, 3, 4];
var ys = filter.call(
xs, x => x % 2
);
console.log(
"xs = [", xs.join(), "]"
);
console.log(
"ys = [", ys.join(), "]"
);
function filter(predicate) {
var xs = []; // new array
for (let x in this) {
if (predicate(x)) {
xs.push(x);
}
}
return xs;
}
Im facing a small issue in Javascript.
I have below Arrays.
var labels = ["labelOne", "labelTwo"];
var values1 = ["89", "9"];
var values2 = ["32", "78"];
Here we can place n number of values arrays like value3,value4....
Now how can i form an array of Objects by combining labels Array and their values are in values arrays. Im expecting the below output after combining above 3 arrays..
var mainArray = [{
label:"labelOne",
value:"89"
},
{
label:"labelTwo",
value:"9"
},
{
label:"labelOne",
value:"32"
},
{
label:"labelTwo",
value:"78"
}]
Can someone please help me to achieve the above output.
Thank you in advance
All that you need is a variable to know how many arrays should be added and access them in a loop using the advantage that Javascript lets you get them like this: window['variableName'] when they are defined in global scope.
var labels = ["labelOne", "labelTwo"];
var values1 = ["89", "9"];
var values2 = ["32", "78"];
var mainArray = [];
// Define a variable to know how many arrays should be added
var maxValues = 2;
function addValues(values) {
// Create new elements and push them into mainArray
mainArray.push({label:labels[0], value:values[0]});
mainArray.push({label:labels[1], value:values[1]});
}
// Do a loop from 1 to maxValues
for(let i = 1; i <= maxValues; i++) {
// Call the function with dynamic variable name
addValues(window['values' + i]);
}
console.log(mainArray);
If the order of your array isn't critical (and then, you might sort it later if it is), you can do like this:
const output = labels.map((label, index) => {
return [{ label, value: values1[index] }, { label, value: values2[index] }];
}).flat();
The map step, will give you an array like this:
[
[{ label: 'labelOne', value: 89 }, { label: 'labelOne', value: 32 }],
[{ label: 'labelTwo', value: 9}, { label: 'labelTwo', value: 78}]
]
By then calling flat, it'll transform it into:
[{ label: 'labelOne', value: 89 }, { label: 'labelOne', value: 32 }, { label: 'labelTwo', value: 9}, { label: 'labelTwo', value: 78}]
Which is what you wanted, from here you can sort the array if that matters for your use case.
I have an array of objects, say the object looks like following:
var row = {
data: 'test',
text: 'test'
};
I want to loop through the array and just get the object with text property.
What is the best way to do it?
So, I want to loop and the object should look like: row = {text: 'test'}
I tried something like below without luck:
arr.forEach(function (item){ //arr is the array of object
return {text: item.text};
});
Use Array.prototype.map for that:
var arr = [{
data: 'testData',
text: 'testText'
}];
var newArr = arr.map(function(item){
return {text: item.data};
});
The result will look like:
[{ text: 'testData' }]
If you want it to be [ {testText: 'testData' }] then:
var arr = [{
data: 'testData',
text: 'testText'
}];
var newArr = arr.map(function(item){
var obj = {};
obj[item.text] = item.data;
return obj;
});
As you want a object with single key value pair, you don't need to store in object form. You can save them as an array.
var array = [
{
text : "text",
data : "data"
},
{
text : "text1",
data : "data1"
}
]
var newArray = array.map(function(item){
return item.data;
});
your output will look like
['text','text1']
I know I can do something like that:
var data = [
{
name: 'test1',
value: 1
}
];
But I want to fill data with dynamic values (from HTML). So I will have var data = []; and how can I fill this one? I know, it must be somewhere on the internet, but I don not know the "right words" to search.
Note: data have to be array filled with objects.
You can use the 'push' method.
var a = [];
a.push({item: 'a', value : 'a'});
console.log(a);
You can use .push method, like so
var data = [];
data.push({ name: 'test1', value: 1});
data.push({ name: 'test2', value: 2});
data.push({ name: 'test3', value: 3});
console.log(data);
I have an array with several category objects, each of which has an items property containing an array of item objects. I want to map each item in each category to an object[] with objects that have the properties value and label. For some reason, I can't perform the concatenation.
var categories = [{
name: "category1",
items: [{
itemId: 1,
name: "Item1"
}, {
itemId: 2,
name: "Item2"
}]
}, {
name: "category2",
items: [{
itemId: 3,
name: "Item3"
}, {
itemId: 4,
name: "Item4"
}]
}];
var items = [];
for(var i = 0; i < categories.length; i++){
items.concat($.map(categories[i].items,function(elem){
return {value:elem.itemId, label:elem.name};
}));
}
console.log(items); //prints []
Expected Result
[{
label: "Item1",
value: "1"
},
{
label: "Item2",
value: "2"
},{
label: "Item3",
value: "3"
},{
label: "Item4",
value: "4"
}
I feel as if I am missing something very basic. I logged the result of the $.map function and it appears to be returning an []. Can anyone figure out the issue?
JSFiddle: http://jsfiddle.net/vymJv/
Another method using straight Javascript:
var x = categories.map(function(val) {
return val.items;
}).reduce(function(pre, cur) {
return pre.concat(cur);
}).map(function(e,i) {
return {label:e.name,value:e.itemId};
});
Output: x = [{label: "Item1", value: 1}, {label: "Item2", value: 2}, …]
The concat() method is used to join two or more arrays.
This method does not change the existing arrays, but returns a new
array, containing the values of the joined arrays.
http://jsfiddle.net/vymJv/1/
for(var i = 0; i < categories.length; i++){
items = items.concat($.map(categories[i].items, function(elem) {
return {value: elem.itemId, label: elem.name};
}));
}
updated with flatMap(not compatible with IE)
categories.flatMap((categories) => categories.items)
flatMap() method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level.
const items = categories
.map(category => category.items)
.reduce((prev, current) => [...prev, ...current])
.map((e, i) => ({ label: e.name, value: e.itemId }));
We could extend the array prototype by creating concatAll which will concatenate all of your arrays by iterating over each subarray, dumping each value into a new array.
Array.prototype.concatAll = function() {
var results = [];
this.forEach(function(subArray) {
subArray.forEach(function(subArrayValue) {
results.push(subArrayValue);
});
});
return results;
};
Then, we can get the desired result with the following:
let items = categories.map(function(category) {
return category.items.map(function(item) {
return {label: item.name, value: item.itemId};
});
}).concatAll();
We get the items by translating each category into an array of items. Because we have two categories, we will end up with two arrays of items. By applying concatAll on the final result, we flatten those two arrays of items and get the desired output.
This piece of code solves your task using a functional programming approach:
var items = [].concat.apply([], categories.map(cat =>
cat.items.map(elem => ({ value:elem.itemId, label:elem.name })))
)
Explanation: Function.prototype.apply() has the syntax fun.apply(thisArg, [argsArray]) and lets us provide parameters to a function in an array. Array.prototype.concat() combines an arbitrary amount of parameters into one array. If we now write Array.prototype.concat.apply([], [category1Items, ..., categoryNItems]), it actually equals [].concat(category1Items, ..., categoryNItems), which concatenates all parameters together. You can also replace Array.prototype.concat by [].concat to keep it shorter. Otherwise we just use standard mapping to get the job done.
You could also split the code apart a bit more for clarity:
function getItem(elem){
return {value:elem.itemId, label:elem.name};
}
function getCategoryItems(cat) {
return cat.items.map(getItem);
}
function flatten(arr) {
return Array.prototype.concat.apply([], arr);
}
var items = flatten(categories.map(getCategoryItems));