I have two arrays one with label date i.e [Date, Date, Date ...] and
the other with the actual date data i.e [2021-11-26, 2021-11-25, ...].
I want to combine these two arrays such that I get array of objects such as [ { Date: 2021-11-26}, {Date:2021-11-25}, {..}, ...].
I have tried these two methods
obj = {};
for (var i = 0, l = date_label.length; i < l; i += 1) {
obj[date_label[i]] = data_date[i]
}
console.log(obj);
and
_.zipObject(date_label, data_date);
However it only ends up giving me the last date of my data set, in an object data structure ie { Date: 1999-11-24}
The keys inside an object / associative array are unique. Your obj is such a thing. If you turn it into a regular array and push new objects into it, it will work.
const obj = [];
for (let i = 0, l = date_label.length; i < l; i++) {
obj.push({[date_label[i]]: data_date[i]})
}
console.log(obj);
You should probably assert that both your arrays have the same length.
The issues you are facing is that your date_label are the same and the loop are replacing the dates on the same label, again and again, you just need to change the label name and give unique to each one or you change them into the loop as well like this (obj[date_label[i] + str(i)] = data_date[i]).
date_label = ['date1', 'date2', 'date3', .....]
obj = {};
for (var i = 0, l = date_label.length; i < l; i += 1) {
obj[date_label[i]] = data_date[i]
}
console.log(obj);
obj is of type array not object.
data_date needs to be in string format.
for(var i= 0; i<data_date.length-1;i++) {
obj.push({"Date":date_date[i]}) }
with array reduce
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
var myFinalArray = data_date.reduce(
(previousValue, currentValue, currentIndex, array) => ({
currentValue: date_label[currentIndex]
}), {});
Hello AshleyCrasto,
Welcome to Stackoverflow.
Sol : Well, the other members have given solution on how to achieve the desired result. I will emphasize on why you are getting the single object.
it only ends up giving me the last date of my data set, in an object data structure ie { Date: 1999-11-24}
You need to understand how references work in JavaScript. Heres the catch,
As the values in date_label are all same
[Date, Date, Date ...]
When you use,
obj[date_label[i]] = data_date[i]
Everytime, it get executed the same key value will be keep updating instead of creating new key and new value. Because the same values holds same reference.
So, first time {"date" : "somevalue"} will be there, then
second time {"date" : "somevalue2"}, the value of key "date" will be updated
with new value. This is due to same key.
Therefore, you need to take of this thing. For your better understanding here is my code: (same as others but elaborately)
const date_label = ["date","date"]
const data_date = [2021-11-26, 2021-11-25]
function returnObj(label, value){
//this will return a new object with provided label and value.
const Obj = {};
Obj[label] = value
return Obj
}
let listOfObjects = []
for(let i=0 ; i< date_label.length ; i++){
//new object will be added to list.
const obj = returnObj(date_label[i],data_date[i])
listOfObjects.push(obj)
}
console.log(listOfObjects)
Related
i am new to javascript and while working on a little project i have a problem ,
i have an array which contains the day splitted into quarters like that
['09:00', '09:15', '09:30', '09:45']
i want to create an object with keys that are the values of this array like that :
var obj = {
'09:00': false ,
'09:15': true ,
'09:30': false
....
}
but i don't want to do it manually because the object will contain time until 00:00 so i will have to write a lot of code while i think it is possible to do it automatically ,
i tried fromEntries() method but it gives me a list of key value pairs when i want just to set the keys of the object .
Any solution ?
You can simple use a for-loop like:
const arr = ['09:00', '09:15', '09:30', '09:45'];
let obj = {};
for (var i = 0; i < arr.length; ++i)
obj[arr[i]] = '';
console.log(obj);
I don't know the logic of true and false so i assigned an empty string.
Your intuition was good: Object.fromEntries() does the job.
But you have to build an array like this:
[['09:00',true ], ['09:30', true] /*...*/]
In order to do this, a simple .map() can help
Object.fromEntries(
['09:00', '09:15', '09:30', '09:45'].map(hour=>[hour, true])
)
You can replace true with getStatusFromHour(hour) and then build a function that sets the right boolean to the selected hour.
You can write a simple for loop and append the data to the object with the required state.
Like:
var arr = ['09:00', '09:15', '09:30', '09:45', '10:00'];
var obj = {};
for(var i = 0; i < arr.length; i++) {
obj[arr[i]] = false;
}
I have an simple javascript array that may contain duplicates or maynot contain duplicates.
var names = [
['aaa','pin/test1.html'],
['bbb','pin/test2.html'],
['ttt','test.html'],
['ggg','test.html'],
['yyy','un/777.html'],
['ggg','test3.html'],
['nnn','test3.html'],
['eee','n/777.html'],
['sss','pin/test1.html'],
['xxx','pin/test2.html'],
['ppp','pin/test1.html'],
];
I need to find the duplicate filepath and put their name into new array. If there is no duplicate then assign its name in first and then assign '' after two values. I could point all the codes that I have tried but it doesnt work. I accept jquery solution also. The expected outcome is this.
var outcome = [
[['aaa','sss','ppp'], 'pin/test1.html'],
[['bbb','eee','xxx'], 'pin/test2.html'],
[['ttt','ggg',''], 'test.html'],
[['yyy','',''], 'un/777.html'],
[['ggg','nnn',''], 'test3.html'],
];
What I have tried is this
for (var i = 0; i < arr.length; i++) {
var uniqueNames = [];
$.each(arr[i], function (i, el) {
if ($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});
console.log(uniqueNames);
}
You could take a hash table and an array of empty strings and find the next slot for the value.
The array is reduced by taking an object as accumulator and a destructure array as value (the first part of the array) and key (the second part, aka filepath).
Inside of Array#reduce, a property check with the key is made and if undefined, an array with the wanted structure (array with two items, the first is an array with three emty spaces and the key) is being assigned by using a logical nullish assignment ??=.
The next line assigns the value to the next free slot, an item with an empty string.
Finally the accumulator is returned.
To get only an array as result, a conversion of the values of the object takes place.
let names = [['aaa','pin/test1.html'], ['bbb','pin/test2.html'], ['ttt','test.html'], ['ggg','test.html'], ['yyy','un/777.html'], ['ggg','test3.html'], ['nnn','test3.html'], ['eee','n/777.html'], ['sss','pin/test1.html'], ['xxx','pin/test2.html'], ['ppp','pin/test1.html']],
grouped = Object.values(names.reduce((r, [v, k]) => {
r[k] ??= [Array(3).fill(''), k];
r[k][0][r[k][0].indexOf('')] = v;
return r;
}, {}));
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
const aux = (names) => {
const hash = {};
let max = 0;
names.forEach(ele => {
if (!hash[ele[1]]) hash[ele[1]] = [];
hash[ele[1]].push(ele[0]);
max = Math.max(hash[ele[1]].length, max);
});
return Object.keys(hash).map(ele => [[...hash[ele], ...Array(max -hash[ele].length).fill("")], ele]);
}
var names = [
['aaa','pin/test1.html'],
['bbb','pin/test2.html'],
['ttt','test.html'],
['ggg','test.html'],
['yyy','un/777.html'],
['ggg','test3.html'],
['nnn','test3.html'],
['eee','n/777.html'],
['sss','pin/test1.html'],
['xxx','pin/test2.html'],
['ppp','pin/test1.html'],
];
console.log(aux(names))
This might help
You do not need jQuery for dealing with regular JS structure, you can achieve what you want with a simple code like this:
var names = [['aaa','pin/test1.html'],['bbb','pin/test2.html'],['ttt','test.html'],['ggg','test.html'],['yyy','un/777.html'],['ggg','test3.html'],['nnn','test3.html'],['eee','n/777.html'],['sss','pin/test1.html'],['xxx','pin/test2.html'],['ppp','pin/test1.html'],];
let lengthToFill = 0;
// collecting all the duplicates into a map
const pathMap = {};
names.forEach(name => {
// just in case if you're not familiar with array destructuring
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
const [pathName, path] = name;
// make sure we have an array to deal with
// just in case you're not familiar with Nullish coalescing operator (??)
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
pathMap[path] = pathMap[path] ?? [];
pathMap[path].push(pathName);
// tracking the max number of elements we're adding into a single entry
lengthToFill = Math.max(lengthToFill, pathMap[path].length);
});
const result = Object.entries(pathMap).map(entry => {
// constructing new array entry based on the data we've collected so far
return [
entry[1].concat(Array(lengthToFill - entry[1].length).fill('')),
entry[0],
];
});
console.log(result);
This solution will work for any number of elements that you'd like to fill the array with ''. It makes sure that the length of final listing is the same for all entries.
I have an array of objects which contain certain duplicate properties: Following is the array sample:
var jsonData = [{x:12, machine1: 7}, {x:15, machine2:7},{x:12, machine2: 8}];
So what i need is to merge the objects with same values of x like the following array:
var jsonData = [{x:12, machine1:7, machine2:8}, {x:15, machine2:7}]
I like the lodash library.
https://lodash.com/docs#groupBy
_.groupBy(jsonData, 'x') produces:
12: [ {x=12, machine1=7}, {x=12, machine2=8} ],
15: [ {x=15, machine2=7} ]
your desired result is achieved like this:
var jsonData = [{x:12, machine1: 7}, {x:15, machine2:7},{x:12, machine2: 8}];
var groupedByX = _.groupBy(jsonData, 'x');
var result = [];
_.forEach(groupedByX, function(value, key){
var obj = {};
for(var i=0; i<value.length; i++) {
_.defaults(obj, value[i]);
}
result.push(obj);
});
I'm not sure if you're looking for pure JavaScript, but if you are, here's one solution. It's a bit heavy on nesting, but it gets the job done.
// Loop through all objects in the array
for (var i = 0; i < jsonData.length; i++) {
// Loop through all of the objects beyond i
// Don't increment automatically; we will do this later
for (var j = i+1; j < jsonData.length; ) {
// Check if our x values are a match
if (jsonData[i].x == jsonData[j].x) {
// Loop through all of the keys in our matching object
for (var key in jsonData[j]) {
// Ensure the key actually belongs to the object
// This is to avoid any prototype inheritance problems
if (jsonData[j].hasOwnProperty(key)) {
// Copy over the values to the first object
// Note this will overwrite any values if the key already exists!
jsonData[i][key] = jsonData[j][key];
}
}
// After copying the matching object, delete it from the array
// By deleting this object, the "next" object in the array moves back one
// Therefore it will be what j is prior to being incremented
// This is why we don't automatically increment
jsonData.splice(j, 1);
} else {
// If there's no match, increment to the next object to check
j++;
}
}
}
Note there is no defensive code in this sample; you probably want to add a few checks to make sure the data you have is formatted correctly before passing it along.
Also keep in mind that you might have to decide how to handle instances where two keys overlap but do not match (e.g. two objects both having machine1, but one with the value of 5 and the other with the value of 9). As is, whatever object comes later in the array will take precedence.
const mergeUnique = (list, $M = new Map(), id) => {
list.map(e => $M.has(e[id]) ? $M.set(e[id], { ...e, ...$M.get(e[id]) }) : $M.set(e[id], e));
return Array.from($M.values());
};
id would be x in your case
i created a jsperf with email as identifier: https://jsperf.com/mergeobjectswithmap/
it's a lot faster :)
Lets say I have this object here:
var items = [
{name:"Foo"},
{name:"Bar"},
{name:"foo"},
{name:"bar"},
{name:"foobar"},
{name:"barfoo"}
];
Since it only has one item in each object, I want to just return a list of them.
I tried this:
var getSingle = function(rows){
var items = [];
//This should only return one column
for (var i = 0; i < rows.length; i++) {
var r = rows[i];
var c = 0;
for (var n in r) {
if(c == 0)
items.push(r[n]);
c += 1;
}
}
return items;
}
But it doesn't seem to work. Any thoughts?
PS. name could be anything.
I used a different approach than the others, because I make two assumptions:
1/ you do not know the name of the key, but there is only one key for every item
2/ the key can be different on every item
I will give you a second option, with the second assumption as: 2/ all item have only one key but that's the same for all of them
First Options :
var items = [
{name:"Foo"},
{name:"Bar"},
{name:"foo"},
{name:"bar"},
{name:"foobar"},
{name:"barfoo"}
];
// object keys very simple shim
Object.keys = Object.keys || function(o) {
var result = [];
for(var name in o) {
if (o.hasOwnProperty(name))
result.push(name);
}
return result;
};
// function to get the value of every first keys in an object
// just remember that saying "first key" does not make real sense
// but we begin with the assumption that there IS ONLY ONE KEY FOR EVERY ITEM
// and this key is unknown
function getFirstKeysValues(items) {
var i = 0, len = items.length, item = null, key = null, res = [];
for(i = 0; i < len; i++) {
item = items[i];
key = Object.keys(item).shift();
res.push(item[key]);
}
return res;
}
console.log(getFirstKeysValues(items)); //["Foo", "Bar", "foo", "bar", "foobar", "barfoo"]
Second options will use a map, because we believe that every child possess the same key (I wouldn't use this one, because I do not like .map that much - compatibility):
var items = [
{name:"Foo"},
{name:"Bar"},
{name:"foo"},
{name:"bar"},
{name:"foobar"},
{name:"barfoo"}
];
// object keys very simple shim
Object.keys = Object.keys || function(o) {
var result = [];
for(var name in o) {
if (o.hasOwnProperty(name))
result.push(name);
}
return result;
};
// function to get the value of every first keys in an object
// just remember that saying "first key" does not make real sense
// but we begin with the asumption that there IS ONLY ONE KEY FOR EVERY ITEM
// and this key is unknown but the same for every child
function getFirstKeysValues(items) {
var key = items.length > 0 ? Object.keys(items[0]).shift() : null;
items = items.map(function (item) {
return item[key];
});
return items;
}
console.log(getFirstKeysValues(items));
This is usually accomplished using the map method, see the documentation here.
var justNamesArray = items.map(function(elem) { return elem.name});
The documenation page also includes a useful shim, that is a way to include it in your code to support older browsers.
Accompanying your request in the edit, if you would just like to get those that contain this property there is a nifty filter method.
var valuesWithNamePropert= items.filter(function(elem) { return elem.hasOwnProperty("name")});
You can chain the two to get
var justNamesWhereContains = items.filter(function(elem) { return elem.hasOwnProperty("name")}).
.map(function(elem) { return elem.name});
This approach (mapping and filtering), is very common in languages that support first order functions like JavaScript.
Some libraries such as underscore.js also offer a method that does this directly, for example in underscore that method is called pluck.
EDIT: after you specific that the property can change between objects in the array you can use something like:
var justReducedArray = items.map(function(elem) { for(i in elem){ return elem[i]}});
your var items = [] is shadowing your items parameter which already contains data. Just by seeing your code I thought that maybe your parameter should be called rows
If you're in a world >= IE9, Object.keys() will do the trick. It's not terribly useful for the Array of Objects, but it will help for the iteration of the Array (you would use Array.forEach to iterate the array proper, but then you would use the Object.keys(ob)[0] approach to get the value of the first property on the object. For example:
var someArr = [{ prop1: '1' },{ prop2: '2' },{ prop3: '3' }];
var vals = [];
someArr.forEach( function(obj) {
var firstKey = Object.keys(obj)[0];
vals.push(obj[firstKey]);
});
//vals now == ['1','2','3']
Obviously this isn't null safe, but it should get you an array of the values of the first property of each object in the original array. Say that 3 times fast. This also decouples any dependency on the name of the first property--if the name of the first property is important, then it's a trivial change to the forEach iteration.
You can override the Array.toString method for items, so using String(items) or alert(items) or items+='' will all return the string you want-
var items = [{name:"Foo"}, {name:"Bar"},{name:"foo"},
{name:"bar"},{name:"foobar"},{name:"barfoo"}];
items.toString= function(delim){
delim=delim || ', ';
return this.map(function(itm){
return itm.name;
}).join(delim);
}
String(items)
/* returned value: (String)
Foo, Bar, foo, bar, foobar, barfoo
*/
instead of the default string-'[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]'
I would like to create a structure within javascript. I have a pair of informations, I would like to use, example:
array[1] = new Struct();
array[1].name = "parameter-name";
array[1].value = "parameter-value";
array[2] = new Struct();
array[2].name = "parameter-name2";
array[2].value = "parameter-value2";
This can be on a diffrent page with diffrent values, maybe on element within my array, maybe 2-20..
Later, within my generic javascript, I would like to parse the array and continue with my parameters, example:
for(i=1 to length_of_my_array) {
_tag.array[i].name = array[i].value;
}
How can I realize this with pure javascript? Thanks for any hint!
As long as you don't want any fancy features, it's really easy to create such structures in JavaScript. In fact, the code you posted will almost work, if you replace the new Struct() with this:
array[1] = {};
This creates an empty object, and you can put any properties you want in it, such as name and value.
To create an array, you can do something like this:
var array = []; // empty array
// object literal notation to create your structures
array.push({ name: 'abc', value: 'def' });
array.push({ name: 'ghi', value: 'jkl' });
...
And to iterate over the array:
for (var i = 0; i < array.length; i++) {
// use array[i] here
}
It would be good to find out more regarding the problem you are attempting to resolve.
I don't think there is an object in JavaScript called Struct, unless you define one.
I think what you are looking for is a JavaScript object instead of Struct. There are a number of ways to create a new object, and they can be nested in an array or in other objects.
myArray[0] = new Object();
myArray[0].name = "parameter-name";
myArray[0].value = "parameter-value";
myArray[1] = new Object();
myArray[1].name = "parameter-name2";
myArray[1].value = "parameter-value2";
Notice that I have changed your code in a couple of ways:
1. "array" is named "myArray" to clarify that we are referring to a particular array.
2. The first instance of myArray is 0. Arrays start at 0 in Javascript.
3. Struct is changed to Object.
myarray = [
{
"name":"parameter-name",
"value":"parameter-value"
},
{
"name":"parameter-name2",
"value":"parameter-value2"
}
];
This is an alternative syntax for doing the same thing. It uses "literal notation" to designate an array (the square brackets), and the objects (the curly brackets).
for(var i = 0; i < myArray.length; i++) {
for(key in myArray[i]) {
alert(key + " :: " myArray[i][key]);
}
}
This will loop over the array and alert you for each property of the object.
alert(myArray[0]['value']) //parameter-value
myArray[0]['value'] = "bar";
alert(myArray[0]['value']) //bar
Each property of each object can also be assigned a new value.
You can define arrays and generic objects in pure JavaScript/json:
var array = []; // empty array
array.push({name: 'parameter-name', value: 'parameter-value'});
array.push({name: 'parameter-name2', value: 'parameter-value2'});
console.log(array);
// Output:
// [Object { name="parameter-name", value="parameter-value2"}, Object { name="parameter-name2", value="parameter-value2"}]
You can also define the same array like so:
var array = [
{name: 'parameter-name', value: 'parameter-value'},
{name: 'parameter-name2', value: 'parameter-value2'}
];
As far as looping through the array:
for (var i = 0; i<array.length; i++) {
var elem = array[i];
console.log(elem.name, elem.value);
}
// Outputs:
// parameter-name parameter-value2
// parameter-name2 parameter-value2
I'd store object literals in the array, like so:
var myArray = [];
myArray[0] = {name:"some name", value:"some value"};
myArray[1] = {name:"another name", value:"another value"};
for (i=0; i < myArray.length; i++) {
console.log(myArray[i].name + ' / ' + myArray[i].value);
}
// initialize empty array
var myArray = [];
// fill it with an object - the equivalent of a struct in javascript
myArray.push({
name: 'example-name'
value: 'example-value'
});
// repeat as neccessary
// walking through the array
for (var i = 0; i < myArray.length; i++)
{
// retrieving the record
record = myArray[i];
// and accessing a field
doSomething(record.name);
}
var array = {paramName: 'paramValue', paramName2: 'paramValue2'};
for(i in array) {
_tag.i = array.i;
}
There is no "Struct" in JavaScript only Object
my_array = new Array();
my_array.push({name: 'john', age:31});
my_array.push({name: 'da_didi', age:120});
for (i=0; i<my_array.length; i++)
{
alert(my_array[i].name);
}
How about
function Struct(name, value) {
this.name = name;
this.value = value;
}
arr[0] = new Struct("name1", "value1");
Javascript objects are loose objects: properties can be added and removed dynamically. So making a new Struct(), as you suggest, does -not- guarantee that the returned object will always have the properties you expect it to have. You have to check the availability of properties at the point of usage (duck typing):
var i, element;
for (i = 0; i < array.length; i++) {
element = array[i];
if (Object.hasOwnProperty.call(element, "name")
&& Object.hasOwnProperty.call(element, "value")) {
_tag[element.name] = element.value;
}
}
(Also, I'm just guessing that _tag is an object itself, but that wasn't clear from your example.)
You could probably use a more succinct syntax, but that depends heavily on the values of the properties. For example, you -might- be able to use something like this:
var i, element;
for (i = 0; i < array.length; i++) {
element = array[i];
if (element.name && element.value) {
_tag[element.name] = element.value;
}
}
But you need to realize that the above condition will be false not only if one or both of the properties (name and value) are undefined but also if the value of either or both refers to the empty string, null, 0, NaN, or false.