how to push into an array with javascript? - javascript

I'm trying to add into an array. I don't know how to traverse and add objects correctly.
I have data array:
const data = [
{
1: "Apple",
2: "Xiaomi"
}
];
const list = [];
data.forEach(function(key, value) {
console.log("key", key);
})
console.log(list)
I want this effect to be as follows:
list: [{
{
value: 1,
title: 'Apple'
},
{
value: 2,
title: 'Xiaomi'
}
}]

Your expected output is invalid. You can first retrieve all the values from the object with Object.values(). Then use Array.prototype.map() to form the array in the structure you want.
Try the following way:
const data = [
{
1: "Apple",
2: "Xiaomi"
}
];
const list = Object.values(data[0]).map((el,i) => ({value: i+1, title: el})) ;
console.log(list);
You can use the existing key of the object with Object.entries() like the following way:
const data = [
{
1: "Apple",
2: "Xiaomi"
}
];
const list = Object.entries(data[0]).map(item => ({value: item[0], title: item[1]}));
console.log(list);

I'll go ahead and make the assumption that data is an object of key/value pairs and you want to transform it to an array of objects.
// Assuming you have an object with key/value pairs.
const data = {
1: "Apple",
2: "Xiaomi"
};
// Convert the data object into an array by iterating over data's keys.
const list = Object.keys(data).map((key) => {
return {
value: key,
title: data[key]
}
});
console.log(list)
Output:
[
{
value: '1',
title: 'Apple'
},
{
value: '2',
title: 'Xiaomi'
}
]
If you actually need value to be numbers instead of strings, you can do it this way:
const list = Object.keys(data).map((key) => {
return {
value: Number(key),
title: data[key]
}
});
And if you are OK with using a more modern version of JavaScript (ECMAScript 2017) this works nicely:
const data = {
1: "Apple",
2: "Xiaomi"
};
// Using Object.entries gives you the key and value together.
const list = Object.entries(data).map(([value, title]) => {
return { value, title }
});

You could do something like this:
const data = ['Apple', 'Xiaomi'];
const result = data.map((item, index) => ({value: index, title: item}));
console.log(result);

If the idea is to turn key names into values and those are not necessarily autoincremented numbers you might want to look at Object.entries():
const data = {1: "Apple", 2: "Xiaomi"};
const res = Object.entries(data).map(entry => ({value: entry[0], title: entry[1]}));
console.log(res);

Related

Javascript: How to convert and map an object containing objects into an array?

In Javascript, how to map and convert this object:
{
0: {k1 : v1},
2: {k2 : v2}
}
to this array:
[
{
label: k1,
value: v1
},
{
label: k2,
value: v2
}
]
obs.: one-liners are nice, but all answers are welcome.
I couldn't get the desired result, but I have blindly followed formulas like:
const objectMap = (obj, fn) =>
Object.fromEntries(
Object.entries(obj).map(
([k, v], i) => [i, fn(v, k, i)]
)
)
const cfieldsFinal = objectMap(modcf, (k, v) => ({
label: v,
value: k
}))
and that's ALMOST what I need, except, it's still an object:
output => {0: {label: k1, value: v1}, 1: {label: k2, value: v2}}
So, only a complete noob such as myself would get stuck on this part...
You're very close, you just need to construct the object manually. Start by using Array.values() to convert data to an array. Iterate the array with Array.flatMap() to flatten the sub-arrays create by the internal map. Convert each object to an array of [key, value] pairs. Map each pair, and create an object.
const data = {0: { k1: 'v1' }, 2: { k2: 'v2' }}
const result = Object.values(data) // convert data to an array
.flatMap(o => // map to a flattend array
Object.entries(o) // get the entries of each object
.map(([label, value]) => ({ label, value })) // create a new object from each entry
)
console.log(result)
const foo = {
0: {
k1: "v1"
},
2: {
k2: "v2"
}
};
/*
[
{
label: k1,
value: v1
},
{
label: k2,
value: v2
}
]
*/
const oe = Object.entries;
const bar = oe(foo).map(([k, v]) => {
const [label, value] = oe(v)[0];
return {
label,
value
};
});
console.log(bar);

Query an array of objects in JavaScript, matching against multiple criteria

I'm trying to query an array of objects in JavaScript, and return objects that match a specific filter criteria.
I've managed - thanks to help from others - to filter a simple object, but now I need to apply the same thing to a more complex object.
// Simple object query:
var recipes = {
'soup': {'ingredients': ['carrot', 'pepper', 'tomato']},
'pie': {'ingredients': ['carrot', 'steak', 'potato']},
'stew': {'ingredients': ['steak', 'pepper', 'tomato']}
};
var shoppingList = ['carrot', 'steak', 'tomato', 'pepper']
var result = Object.entries(recipes)//1. get the key-value pairs
.filter(([key, {ingredients}]) => ingredients.every(t => shoppingList.includes(t))) //2. filter them
.map(([key]) => key) //3. get the keys only
console.log(result);
// More complex object:
var itemsTest = [
{
uid: 1,
items: [
{ item: { uid: "a" } },
{ item: { uid: "b" } },
{ item: { uid: "g" } }
]
},
{
uid: 2,
items: [
{ item: { uid: "b" } },
{ item: { uid: "q" } },
{ item: { uid: "f" } }
]
},
}
];
var filter = ["b", "q", "f"]
// Expect filter to return {uid: 2, items}
}
The recipes filter works great. But now I have a more complex array of objects, it seems the same approach isn't possible.
I want to filter itemsTest according to the uid of each item in the items array. I'd be happy to use lodash, if it makes life easier.
I tried to flatten the array of objects using Object.entries(), to no avail.
var flattened = objectMap(itemsList, function(value) {
return Object.entries(value);
});
var result = flattened.filter(([key, { uid }]) =>
uid.every(t => filter.includes(t))
)
I also tried a simplified approach filtering with one value using Array.filter.prototype(), which doesn't work either:
var newArray = flattened.filter(function(el) {
return el.uid <= 2
});
console.log(newArray)
Any help understanding how to navigate an object like this would be great.
You can use Array.find() (or Array.filter() to iterate the array of objects. Now use Array.every(), and for each item check if it's uid is included in the filter array.
const itemsTest = [{"uid":1,"items":[{"item":{"uid":"a"}},{"item":{"uid":"b"}},{"item":{"uid":"g"}}]},{"uid":2,"items":[{"item":{"uid":"b"}},{"item":{"uid":"q"}},{"item":{"uid":"f"}}]}];
const filter = ["b", "q", "f"];
const result = itemsTest.find(({ items }) => // use filter instead of find to get multiple items
items.every(o => filter.includes(o.item.uid))
);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

How to create an array of property/value from an object using Ramda?

I have an object like
const obj = {
apple:'red',
banana:'yellow'
}
I need to return an array with properties/values using ramda.
Example:
[
{
name: 'apple',
value:'red'
},
{
name: 'banana',
value:'yellow'
},
]
A ramda solution:
R.pipe(
R.toPairs,
R.map(R.zipObj(['name', 'value']))
)(obj)
You can achieve that without any 3rd party lib, with Object.entries, that returns an array with an array that contains key & value, map over it to convert it to an object.
const obj = {
apple: 'red',
banana: 'yellow'
};
const result = Object.entries(obj)
.map(([name, value]) => ({
name,
value
}));
console.log(result);

es6 merge two array of objects and override the existing object

I have 2 array of objects:
const arr1 = [{'id':'1' 'value':'yes'}, {'id':'2', 'value':'no'}];
const arr2 = [{'id':'2', 'value':'yes'}];
So, if I try and merge these 2 arrays the result should be:
arrTemp = [{'id':'1', 'value':'yes'}, {'id':'2', 'value':'yes'}];
Basically, it should work similar to Object.assign(), but no matter what I try it does not work. Could anyone please help me in this ?
I modified the data structure. Is it possible to merge them now and get the output.
Thanks
This is how you can get the job done with ES6 spread, reduce and Object.values.
const arr1 = [{
'id': '1',
'value': 'yes'
}, {
'id': '2',
'value': 'no'
}];
const arr2 = [{
'id': '2',
'value': 'yes'
}];
const result = Object.values([...arr1, ...arr2].reduce((result, {
id,
...rest
}) => {
result[id] = {
...(result[id] || {}),
id,
...rest
};
return result;
}, {}));
console.log(result);
const result = Object.entries(Object.assign({}, ...arr1,...arr2)).map(([key, value]) => ({[key]:value}));
You could spread (...) the arrays into one resulting object ( via Object.assign) and then map its entries to an array again.
You could work with a valid ES6 data structure like a map for example:
const 1 = { 1: { string: 'yes' }, 2: { string: 'no' } }
const 2 = { 2: { string: 'yes' }, 3: { string: 'no' } }
const 3 = { ...1, ...2}
This will override your first argument with the second one or just combine them where possible.
Just try it out in your browser it's a lot easier and enhances performance since you will never have to use findById() which is an expensive operation.
In javascript, arrays are simply objects indexed by numbers starting from 0.
So when you use Object.assign on arr1 and arr2 you will override the first item in the arr1 with the first item in arr2 because they are both indexed under the key 0.
your result will be:
[
{ '2': 'yes' },
{ '2': 'no' }
]
(or in object syntax:)
{
0: { '2': 'yes' },
1: { '2': 'no' }
}
Instead of using arrays, you could create an object indexed by the number string (which is how you seem to be thinking of the array in any case).
So you could change your original data structure to make the job easier:
const arr1 = {
'1': 'yes',
'2': 'no'
};
const arr2 = {
'2': 'yes'
};
const result = Object.assign(arr1, arr2);
You could take a Map as reference to the new assigned object in the result array and build first a new array with a copy of the objects and then iterate the second array and update the objects with the same key.
var array1 = [{ 1: 'yes' }, { 2: 'no' }],
array2 = [{ 2: 'yes' }],
getKey = o => Object.keys(o)[0],
map = new Map,
result = array1.map(o => (k => map.set(k, Object.assign({}, o)).get(k))(getKey(o)));
array2.forEach(o => Object.assign(map.get(getKey(o)), o));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Array reduce could come in handy is this case. See example below:
[...arr1, ...arr2].reduce((acc, item) => {
const updated = acc.find(a => a.id === item.id)
if (!updated) {
acc.push(item)
} else {
const index = acc.indexOf(updated)
acc[index] = { ...item, ...acc[index] }
}
return acc
}, [])
simple way to add with exist array of object:
const arr1 = [{ "name":"John", "age":30, "car":"toyata" }];
const arr2 = [{ "name":"Ales", "age":40, "car":"Nissan" }];
Array.prototype.push.apply(arr1, arr2);
Result:=>
console.log(arr1)
For anyone finding this answer at a later point in time. There are a couple of ways that you could want this to work exactly, but you could filter all adjusted elements in the first array, and then combine it with the second array.
const arr3 = [...arr1.filter(item1 => !arr2.find(item2 => item1.id === item2.id)), ...arr2]
Alternatively, you could update the elements in the first array, and then filter them from the second array instead.
You cannot use array.prototype map because the key of arr1 and arr2 have the same value '2'.
You should use something like this
for (var i = 0, l = arr1.length; i < l; i++) {
var key = Object.keys(arr1[i]);
if (!arr2[key]) { arr2[key] = []; }
arr2[key].push(arr1[i][key]);
}
Regards

What is the best way to convert an array of strings into an array of objects in Angular 2?

Let's say I have an array as follows:
types = ['Old', 'New', 'Template'];
I need to convert it into an array of objects that looks like this:
[
{
id: 1,
name: 'Old'
},
{
id: 2,
name: 'New'
},
{
id: 3,
name: 'Template'
}
]
You can use map to iterate over the original array and create new objects.
let types = ['Old', 'New', 'Template'];
let objects = types.map((value, index) => {
return {
id: index + 1,
name: value
};
})
You can check a working example here.
The solution of above problem is the map() method of JavaScript or Type Script.
map() method creates a new array with the results of calling
a provided function on every element in the calling array.
let newArray = arr.map((currentvalue,index,array)=>{
return Element of array
});
/*map() method creates a new array with the results of calling
a provided function on every element in the calling array.*/
let types = [
'Old',
'New',
'Template'
];
/*
let newArray = arr.map((currentvalue,index,array)=>{
return Element of array
});
*/
let Obj = types.map((value, i) => {
let data = {
id: i + 1,
name: value
};
return data;
});
console.log("Obj", Obj);
Please follow following links:
TypeScript
JS-Fiddle
We can achieve the solution of above problem by for loop :
let types = [
"One",
"Two",
"Three"
];
let arr = [];
for (let i = 0; i < types.length; i++){
let data = {
id: i + 1,
name: types[i]
};
arr.push(data);
}
console.log("data", arr);

Categories