I have this array above and I need every property of it
let arr = [{'John': 0}, {'Doe': 50}, {'Marry': 100}]
How could I extract every single key/value of it, once in theory, I don't know any of them?
I have already tried using object.keys but it returns the indexes of my array.
This should work
const arr = [{'John': 0}, {'Doe': 50}, {'Marry': 100}];
// to iterate over each element in the arry
arr.forEach(a => {
// To Iterate over each key in the element object
Object.keys(a).forEach(k => {
// to print the value of the 'k' key
console.log(k + ' : ' + a[k]);
})
})
1) You can use flatMap and Object.keys to get keys from an array of objects.
let arr = [{ John: 0 }, { Doe: 50 }, { Marry: 100 }];
const result = arr.flatMap((o) => Object.keys(o));
console.log(result);
2) To find all values in an array
let arr = [{ John: 0 }, { Doe: 50 }, { Marry: 100 }];
const values = arr.flatMap((o) => Object.values(o));
console.log(values);
3) If you want to find out all keys and values in an object
let arr = [{ John: 0 }, { Doe: 50 }, { Marry: 100 }];
const result = {
keys: [],
values: [],
};
for (let obj of arr) {
Object.entries(obj).map(([k, v]) => {
result.keys.push(k);
result.values.push(v);
});
}
console.log(result);
If you want to collect all the keys and values of a nested array of objects, you can use Array.prototype.reduce and then collect the keys and values of the nested objects in separate nested arrays, using Object.keys() and Object.values() respectively:
const arr = [{'John': 0}, {'Doe': 50}, {'Marry': 100}];
const allKeysAndValues = arr.reduce((acc, cur) => {
acc.keys.push(...Object.keys(cur));
acc.values.push(...Object.values(cur));
return acc;
}, { keys: [], values: [] });
console.log(allKeysAndValues);
A one liner could be
let arr = [{'John': 0}, {'Doe': 50}, {'Marry': 100}]
console.log( arr.map( obj => Object.entries(obj)));
I have these 2 arrays:
productsForSale = ['eggs', 'eggs', 'bread', 'milk'];
soldPrice = [2.70, 2.50, 1.97, 3.29];
yes, the values of the first 2 elements ("eggs") are different but that's meant to be for this question. Now I want to create an array of objects that will look like this:
[
{
eggs: 2.70
},
{
eggs: 2.50
},
{
bread: 1.97
},
{
milk: 3.29
}
]
So far I have this code:
var obj = {};
var arr = [];
productsForSale.forEach((key, i) => {
obj[key] = soldPrice[i];
arr.push(obj);
});
But I don't get the expected output. Can anyone point me in the right dirrection? Thanks
You can use map().
const productsForSale = ["eggs", "eggs", "bread", "milk"];
const soldPrice = [2.7, 2.5, 1.97, 3.29];
const output = productsForSale.map((el, i) => ({ [el]: soldPrice[i] }));
console.log(output);
How to use javascript to change the array to the object format? Thanks!
[ "16-282", "16-311", "16-320", "17-275", "17-276" ]
object format:
[{
id: 16,
Options: [282, 311, 320],
},
{
id: 17,
Options: [275, 276],
}]
My Code:
test() {
var option = ["16-282", "16-311", "16-320", "17-275", "17-276"];
var finalResult = option.map((item, index) => ({id: item, Options: item, }));
console.log(finalResult);
},
What you want is a "groupBy" operation using the id as object keys and a new object as values
Solution using Array#reduce() and a Map
var option = ["16-282", "16-311", "16-320", "17-275", "17-276"];
const group = option.reduce((m, c) => {
const [id, val] = c.split('-');
const obj = m.get(id) || { id, options: [] };
obj.options.push(val);
return m.set(id, obj)
}, new Map)
console.log([...group.values()])
.as-console-wrapper {
max-height: 100%!important;
top: 0
}
Lets start with your code:
var finalResult = option.map((item, index) => ({id: item, Options: item, }));
Here you are using .map. It will return an array of n length with parsed output.
Based on your output, you need to group the values based on part that is before -. This can be done in many ways, but I'll use for as its easy to understand:
Idea:
Create an object to hold groups. Object and not array as Objects are key-value pair structure. So your groupId would be key and value will be the value to store.
Now loop over the option array.
For every iteration, split item using hyphen(-). First part is your key and second is your value.
Check if this key exists in group. If yes, push current value to the Options array.
If it does not exists, initialize it with default structure:
{ id: groupKey, Options: [ groupValue ] }
Sample:
var option = ["16-282", "16-311", "16-320", "17-275", "17-276"];
var groups = {};
for (var i = 0; i< option.length; i++) {
var parts = option[i].split('-');
var groupKey = parts[0];
var groupValue = parts[1];
// Check if the groupKey exists in group
if (groups[ groupKey ] !== undefined) {
groups[ groupKey ].Options.push(groupValue)
} else {
groups[ groupKey ] = { id: groupKey, Options: [ groupValue ] }
}
}
console.log(groups)
Now that you have groups, you just need to loop over this object and make an array.
An accumulation of above grouping idea and creating array is as follows:
var option = ["16-282", "16-311", "16-320", "17-275", "17-276"];
const groups = option.reduce((acc, item) => {
const [ id, value ] = item.split('-');
acc[ id ] = acc[ id ] || { id, Options: [ ]};
acc[ id ].Options.push(value);
return acc;
}, {});
const result = Object.values(groups);
console.log(result)
.as-console-wrapper {
top: 0;
max-height: 100vh!important;
}
I have [ { key1:value1, key2:value2 }, { key3:value3, key4:value4 }, .... ]. I want to convert it to
{ value1: value2, value3: value4 }
Use Array#reduce to accumulate your object-data. Foreach object take from the values the first and add a new property with this name to the accumulated object with the value from the second object-value.
let array = [ { key1:'value1', key2:'value2' }, { key3:'value3', key4:'value4' }];
let res = array.reduce((acc, cur) => {
values = Object.values(cur);
acc[values[0]] = values[1];
return acc;
}, {});
console.log(res);
Assuming the inner objects always have 2 keys:
const arr = [ { key1:'value1', key2:'value2' }, { key3:'value3', key4:'value4' }]
const obj = {};
for (const innerObj of arr) {
const values = Object.values(innerObj);
obj[values[0]] = values[1];
}
console.log(obj) // { value1: 'value2', value3: 'value4' }
Note: you're question assumes an order for the keys in the inner objects, but that may not be guaranteed
I have:
var keys = [ "height", "width" ];
var values = [ "12px", "24px" ];
And I'd like to convert it into this object:
{ height: "12px", width: "24px" }
In Python, there's the simple idiom dict(zip(keys,values)). Is there something similar in jQuery or plain JavaScript, or do I have to do this the long way?
The simplest ES6 one-liner solution using Array reduce:
const keys = ['height', 'width'];
const values = ['12px', '24px'];
const merged = keys.reduce((obj, key, index) => ({ ...obj, [key]: values[index] }), {});
console.log(merged);
Simple JS function would be:
function toObject(names, values) {
var result = {};
for (var i = 0; i < names.length; i++)
result[names[i]] = values[i];
return result;
}
Of course you could also actually implement functions like zip, etc as JS supports higher order types which make these functional-language-isms easy :D
use lodash.
_.zipObject
Example
_.zipObject(['a', 'b'], [1, 2]);
// ➜ { 'a': 1, 'b': 2 }
As an alternate solution, not already mentioned I think :
var result = {};
keys.forEach((key, idx) => result[key] = values[idx]);
You can combine two arrays with map method, then convert it with Object.fromEntries.
var keys = ["height", "width"];
var values = ["12px", "24px"];
var array = keys.map((el, i) => {
return [keys[i], values[i]];
});
// → [["height", "12px"], ["width", "24px"]]
var output = Object.fromEntries(array);
// → {height: "12px", width: "24px"}
console.log(output);
A functional approach with immutability in mind:
const zipObj = xs => ys => xs.reduce( (obj, x, i) => ({ ...obj, [x]: ys[i] }), {})
const arr1 = ['a', 'b', 'c', 'd']
const arr2 = ['e', 'f', 'g', 'h']
const obj = zipObj (arr1) (arr2)
console.log (obj)
You could use a reduce() function to map the key-value pairs to an object.
/**
* Apply to an existing or new object, parallel arrays of key-value pairs.
*
* #param {string[]} keys - List of keys corresponding to their accociated values.
* #param {object[]} vals - List of values corresponding to their accociated keys.
* #param {object} [ref={}] - Optional reference to an existing object to apply to.
*
* #returns {object} - The modified or new object with the new key-value pairs applied.
*/
function toObject(keys, vals, ref) {
return keys.length === vals.length ? keys.reduce(function(obj, key, index) {
obj[key] = vals[index];
return obj;
}, ref || {}) : null;
}
var keys = [ "height" , "width" ];
var values = [ "12px" , "24px" ];
document.body.innerHTML = '<pre>' + JSON.stringify(toObject(keys, values), null, 2) + '</pre>';
Here's an example with all consts (non-modifying) and no libraries.
const keys = ["Adam", "Betty", "Charles"];
const values = [50, 1, 90];
const obj = keys.reduce((acc, key, i) => {
acc[key] = values[i];
return acc;
}, {});
console.log(obj);
Alternatively, if you'd consider libraries you could use lodash zipobject which does just what you asked.
Now we have Object.fromEntries we can do something like that:
const keys = [ "height", "width" ];
const values = [ "12px", "24px" ];
const myObject = Object.fromEntries(
values.map((value, index) => [keys[index], value])
);
console.log(myObject);
You could transpose the arrays and get the object with the entries.
const
transpose = (r, a) => a.map((v, i) => [...(r[i] || []), v]),
keys = [ "height", "width" ],
values = [ "12px", "24px" ],
result = Object.fromEntries([keys, values].reduce(transpose, []));
console.log(result);
function combineObject( keys, values)
{
var obj = {};
if ( keys.length != values.length)
return null;
for (var index in keys)
obj[keys[index]] = values[index];
return obj;
};
var your_obj = combine( your_keys, your_values);
Here's one which will transform nested arrays into an array of multiple key-value objects.
var keys = [
['#000000', '#FFFFFF'],
['#FFFF00', '#00FF00', '#00FFFF', '#0000FF'],
];
var values = [
['Black', 'White'],
['Yellow', 'Green', 'Cyan', 'Blue'],
];
const zipObj = xs => ys => xs.reduce( (obj, x, i) => ({ ...obj, [x]: ys[i] }), {})
var array = keys.map((el, i) => zipObj (keys[i]) (values[i]));
console.log(array);
Output is
[
{
"#000000": "Black",
"#FFFFFF": "White"
},
{
"#FFFF00": "Yellow",
"#00FF00": "Green",
"#00FFFF": "Cyan",
"#0000FF": "Blue"
}
]
Providing a solution with a for...of loop.
var keys = ["height", "width"];
var values = ["12px", "24px"];
const result = {};
for (let [index, key] of keys.entries())
result[key] = values[index];
console.log(result);
You can also use a library like ramda which has zipObj function.
Example:
const keys = ["height", "width"];
const values = ["12px", "24px"];
const result = R.zipObj(keys, values);
console.log(result);
In the jQuery-Utils project, the ArrayUtils module has a zip function implemented.
//...
zip: function(object, object2, iterator) {
var output = [];
var iterator = iterator || dummy;
$.each(object, function(idx, i){
if (object2[idx]) { output.push([i, object2[idx]]); }
});
return output;
}
//...