I am looking to push only the values of ObjArray into another array called Array.
var Array = [];
var ObjArray = [{item1 : 'Foo'}, {item2 : 'Bar'}];
// Push Values from ObjArray into Array
pushValues(ObjArray, Array);
The expected output would be Array having only ['Foo', 'Bar']
Thanks!
edit: Sorry. I am asking how to push all values from ObjArray into Array.
You can try with Array.prototype.map()
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
And Object.values()
The Object.values() method returns an array of a given object's own enumerable property values.
As you have single value in the object use [0] to return that.
var ObjArray = [{item1 : 'Foo'}, {item2 : 'Bar'}];
var array = ObjArray.map(i => Object.values(i)[0]);
console.log(array);
Using for...of and push()
var array = [];
var ObjArray = [{item1 : 'Foo'}, {item2 : 'Bar'}];
for(var i of ObjArray){
array.push(Object.values(i)[0]);
}
console.log(array);
If your objects have multiple key-value pairs within them you can use a combination of .flatMap() with Object.values() like so:
const objArray = [{a: 'foo', b: 'bar'}, {c : 'baz'}];
const arr = objArray.flatMap(Object.values);
console.log(arr); // ["foo", "bar", "baz"]
However, do note, .flatMap() does have limited browser support, and so, if you need something a little more compatible, you can use .reduce() instead:
const objArray = [{a: 'foo', b: 'bar'}, {c : 'baz'}];
const arr = objArray.reduce((a, o) => [...a, ...Object.values(o)], []);
console.log(arr); // ["foo", "bar", "baz"]
Related
I am looking for some solution to a problem that I faced during completing an assignment. The problem is similar to this that I have tried explaining below.
var arrOfObj = [{a:10 },{a:20},{a:30}, ......]
var arrToMultiply = [2,4,6, .....]
Result I am expecting
const result = [{a:10,result:20},{a:20,result:80},{a:30,result:180}, .....]
how can I multiply each value of array with the value of integer at same index inside object of the array?
You can do it like this:
let arrOfObj = [{a: 10}, {a: 20}, {a: 30}];
let arrToMultiply = [2, 4, 6];
let result = arrOfObj.map((item, index)=> ({...item, result: item.a*arrToMultiply[index]}));
console.log(result);
I'm have an array of strings:
const arr = ["foo", "bar"];
Is it better to check content with indexOf:
if (arr.indexOf("foo") > 0)
Or should I convert it to an object with the strings as fieldnames:
const arrObj = _.keyBy(arr);
/* resulting arrObj = {
foo: "foo",
bar: "bar"
}; */
if(arrObj.foo)
I'm getting the array only once, so I'm only converting to object once, but I'm checking for the strings repeatedly.
I'm thinking the indexOf is O(n) and field access is O(1).
Say I have the follow array of objects storing a single key\value pair:
var someArray = [
{foo: 1},
{bar: 2}
];
I would like to flatten this array into a single object, where each key from the original objects become a property of the new single object like so:
someObject = {
foo: 1,
bar: 2
}
I will always have unique keys, and only ever one key\value pairing.
I know if I loop over the array in a foreach, then I can only access the index and value of the item, e.g.
0: {foo: 1}
I want to be able to loop over, and when accessing the item read the key and value separately so I can append onto my new object.
I feel like lodash should be able to help here, but I'm struggling to find whic of their methods could help.
Can someone point me in the right direction?
Thanks
No need for lodash here you can just use Object.assign() and spread syntax.
var someArray = [
{foo: 1},
{bar: 2}
];
var obj = Object.assign({}, ...someArray)
console.log(obj)
You can also use apply instead of spread syntax
var obj = Object.assign.apply({}, someArray)
var someArray = [
{foo: 1},
{bar: 2}
];
var obj = Object.assign.apply({}, someArray)
console.log(obj)
You could iterate and use Object.assign to get a new object with all properties.
var someArray = [{ foo: 1 }, { bar: 2 }],
result = someArray.reduce(function (r, a) {
return Object.assign(r, a);
}, {});
console.log(result);
This can be done quickly using reduce and Object assign:
var someArray = [
{foo: 1},
{bar: 2}
];
var result = someArray.reduce((acc, obj) => Object.assign(acc, obj), {})
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Using .slice(), I can deep copy a Javascript Array of primitive types, for example:
var arr = [1,2,3,4];
var newArr = arr.slice();
newArr.push(5);
console.log(arr); // [1,2,3,4]
console.log(newArr); // [1,2,3,4,5]
However, If I add a property to arr like so:
arr.prop1 = 5;
and do the same:
var arr = [1,2,3,4];
arr.prop1 = 8;
arr.prop2 = 9;
var newArr = arr.slice();
newArr.push(5);
console.log(arr); // [1, 2, 3, 4, prop1: 9, prop2: 8]
console.log(newArr); // [1, 2, 3, 4, 5]
The property values do not carry over to newArr
I have considered not using .slice() and looping over the property values of arr instead, assigning them to newArr, using :
for (var key in arr) {
if (arr.hasOwnProperty(key)) {
newArr[key] = arr[key];
}
}
console.log(arr); // [1, 2, 3, 4, prop1: 9, prop2: 8]
console.log(newArr); // [1, 2, 3, 4, 5, prop1: 9, prop2: 8]
Is this going to be the quickest way to deep copy these arrays with properties? Is there in easier or cleaner way I can do this using .slice() or another array method? I am doing this operation tens of thousands of times and want it to be as clean and efficient as possible
You are trying to mix an array and object(to make an array behave like an object).
JavaScript array has numeric indexed items.
JavaScript object has string indexed items.
Arrays have a length property that tells how many items are in the array and is automatically updated when you add or remove items to the array.But ...
var arr = [1,2,3,4], newArr = arr.slice();
arr.prop1 = 7;
console.log(arr.length);
The output is 4, though you would expect it to be 5.But arr.prop1 = 7 does not actually add to the array.Setting a string parameter adds to the underlying object.
The length property is only modified when you add an item to the array, not the underlying object.The expression newArr = arr.slice() assigns a new array to newArr, so it remains an array and behaves like a pure array.
The property values do not carry over to newArr
If you still want to proceed using mixed numeric/string indexed sequences, cloning them, try using Object.assign() function. This should be the easiest way for your case:
The Object.assign() method is used to copy the values of all
enumerable own properties from one or more source objects to a target
object.
console.log(Object.assign(newArr, arr));
The output:
[1, 2, 3, 4, prop1: 7]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
How about using Object.create(proto)
var arr = [1,2,3,4];
arr.prop1 = 8;
arr.prop2 = 9;
var newArr = Object.create(arr);
newArr.prop1 = 12;
console.log(arr.prop1) // 8
console.log(newArr.prop1) // 12
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
Let's say I have this Array of objects:
[300: {a:"some", b:"value"}, 301: {a: "another", b: "val"} ...]
I have that kind of object and I am iterating using recursive function, and there's no way I will change my counter to start at 300, I always start at 0.
I am thinking of a solution, to remove the keys from the agrray so that I will have an array like so:
[{a:"some", b:"value"}, {a: "another", b: "val"} ...]
How do I do that in javascript? Also, if there is another way that would be much faster than creatng a function that will remove keys, it will be much better.
This will give you a syntax error (SyntaxError: missing ] after element list):
var data = [300: {a:"some", b:"value"}, 301: {a: "another", b: "val"}];
You mean this:
var data = {300: {a:"some", b:"value"}, 301: {a: "another", b: "val"}};
And to convert that into an array, loop over the object and push each value into a new array:
var arr = [];
for (var k in data) {
arr.push(data[k]);
}
Fiddle
If you meant that the initial structure of array is this:
var data = [{300: {a:"some", b:"value"}}, {301: {a: "another", b: "val"}}];
then this should work (result array):
var result = [];
var data = [{300: {a:"some", b:"value"}}, {301: {a: "another", b: "val"}}];
for(var i =0; i < data.length; i++){
for(var key in data[i]) {
if(data[i].hasOwnProperty(key)) {
result.push(data[i][key]);
break;
}
}
}
There is a point here that should be clarified. When you have a Array object which its values starts from 300 as its indexes, it means you have 300 indexes with undefined values, but if it is just an Array-like object it could be totally different.
Let's say this is not an Array-like and is an actual Array, so you have to filter it so that all the undefined values get removed from your array, so your array should be like:
var arr = [/*0*/undefined, ..,/*299*/undefined, /*300*/{a:"some", b:"value"}, /*301*/ {a: "another", b: "val"} ...]
var result = arr.filter(function(value,index){
return (value !== undefined);
});
but what you have mentioned in your question, is more likely a javascript object, so to do what you want you can do:
var myObj = {300: {a:"some", b:"value"}, 301: {a: "another", b: "val"} };
var result = {};
for(var key in obj){
if(obj.hasOwnProperty(key)){
result.push(obj[key]);
}
}
in this for loop hasOwnProperty function helps you make sure if it is one of the actual object values, and not other possible keys from the object's prototype chain.