Change name JSON in array - javascript

I am trying to rename the json but it generates the following error
var kvArray = [
{0: 'cat', 1: 1, 2: "sunt"},
{0: 'dog', 1: 2, 2: "qui"},
{0: 'mouse',1: 3, 2: "repell"}
];
var newArray = kvArray.map((elm) => {
var mappedElm = { animal: elm.0, age: elm.1, name: elm.2};
return mappedElm;
});
console.log(newArray)

The object represented in the JSON is an numerically indexed array, not an object.
You probably need to use the [] index contstruct as follows
var kvArray = [
{0: 'cat', 1: 1, 2: "sunt"},
{0: 'dog', 1: 2, 2: "qui"},
{0: 'mouse',1: 3, 2: "repell"}
];
var newArray = kvArray.map((elm) => {
var mappedElm = { animal: elm[0], age: elm[1], name: elm[2]};
return mappedElm;
});
console.log(newArray)

Related

Convert array to object without sorting keys in javascript

I have an object
{
1: {id: 1, first: 1, last: 5}
2: {id: 2, first: 6, last: 10}
3: {id: 3, first: 11, last: 15}
}
I need to reverse the items order without sorting the keys so the final result is:
{
1: {id: 3, first: 11, last: 15}
2: {id: 2, first: 6, last: 10}
3: {id: 1, first: 1, last: 5}
}
Is this possible?
I tried to convert it into array and then into an object but the new object starts with key 0 while I need it to start with key 1:
let array = [];
Object.values(this.props.items)
.sort()
.reverse()
.forEach(function(b) {
array.push(b);
});
const newItems = Object.assign({}, array);
// Result:
{
0: {id: 3, first: 11, last: 15}
1: {id: 2, first: 6, last: 10}
2: {id: 1, first: 1, last: 5}
}
EDIT
Worth mention that my object is typed:
Btw this.props.items is typed TypeScript object eg. Section.Item[]
You could get keys and values and assign the popped value to the keys.
var object = { 1: { id: 1, first: 1, last: 5 }, 2: { id: 2, first: 6, last: 10 }, 3: { id: 3, first: 11, last: 15 } },
values = Object.values(object)
Object.keys(object).forEach(k => object[k] = values.pop());
console.log(object);
You could use fromEntries
const data = {
1: { id: 1, first: 1, last: 5 },
2: { id: 2, first: 6, last: 10 },
3: { id: 3, first: 11, last: 15 },
};
console.log(
Object.fromEntries(
Object.values(data)
.reverse()
.map((val, index) => [index + 1, val])
)
);
Perhaps you can try this
let obj = {
1: {id: 1, first: 1, last: 5},
2: {id: 2, first: 6, last: 10},
3: {id: 3, first: 11, last: 15}
}
const newItems = {}
let totalKeys = Object.keys(obj).length
for (let key in obj) {
newItems[totalKeys] = obj[key];
totalKeys -= 1;
}
console.log(newItems);

Comparing a particular key in 2 array of objects [duplicate]

This question already has answers here:
How to get the difference between two arrays of objects in JavaScript
(22 answers)
Closed 3 years ago.
Is there a way with lodash, where in result I do not have an object that satisfies a particular condition. For example,
o1 = [
{name: "a", id: 2, key: 33},
..,
]
o2 = [
{name: "ab", id: 2, key: 133}
]
Is there a way with lodash where the resultant array only includes the object that does not have the ids already present in o2. For example, resultant object after comparing o1 and o2 must not have the object from o2 because id=2 already exists in o1.
You can use _.differenceBy() and use the id of the point of reference:
const o1 = [{id: 1, name: 'a'},{id: 2, name: 'b'},{id: 3, name: 'c'}]
const o2 = [{id: 1, name: 'b'}]
const result = _.differenceBy(o1, o2, 'id')
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Maybe _.differenceWith?
const o1 = [
{id: 1, name: "a"},
{id: 2, name: "b"},
{id: 3, name: "c"},
]
const o2 = [
{id: 1, name: "b"},
]
const diffed = _.differenceWith(o1, o2, (o1, o2) => o1.id === o2.id)
console.log(diffed)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
You could do this without lodash by using .filter() and creating a Set. Firstly, you can create a set of all the ids in o2. Then, you can filter out any objects from o1 which have an id within the set. By using a set with .has() we are able to make our algorithm more efficient (than say using .includes() on an array).
See example below:
const o1 = [
{name: "a", id: 2, key: 33},
{name: "b", id: 3, key: 34},
{name: "c", id: 4, key: 34}
]
const o2 = [
{name: "d", id: 2, key: 134}
]
const o2_ids = new Set(o2.map(({id}) => id));
const result = o1.filter(({id}) => !o2_ids.has(id));
console.log(result); // includes objects with id's that appear in o1 but not in o2
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var o1 = [
{name: "a", id: 77, key: 55},
{name: "a", id: 2, key: 33},
{name: "a", id: 1, key: 55}
]
var o2 = [
{name: "ab", id: 88, key: 133},
{name: "ab", id: 2, key: 133},
{name: "ab", id: 99, key: 133}
]
//sort first
o1.sort((a, b) => {
return a.id-b.id;//sort by id
});
o2.sort((a, b) => {
return a.id-b.id;//sort by id
});
//then compare one by one
function SearchX(OO1,OO2){
var o1_compare_place=0;
var o2_compare_place=0;
while(OO2.length>o2_compare_place && OO1.length>o1_compare_place ){
if(OO2[o2_compare_place].id<OO1[o1_compare_place].id){
o2_compare_place+=1;
}else if(OO2[o2_compare_place].id>OO1[o1_compare_place].id){
o1_compare_place+=1;
}else{
return "Exist Same!";
}
}
return "Different!";
}
document.body.innerHTML = SearchX(o1,o2)
</script>
</body>
</html>
Here you are

How to Map Array values from one Array to Another Array JavaScript?

This is my Code. Where I want to Pass the Values of kvArray to Second Array.
var kvArray = [{key: 1, value: 10},
{key: 2, value: 20},
{key: 3, value: 30}];
var reformattedArray = kvArray.map(obj => {
var payload = {};
payload["rt"];
payload["do"];
payload["f1"];
payload[obj.key] = obj.value;
console.log(payload["rt"]);
return payload;
});
The console.log is coming undefined.
Can anyone help here? I am pretty new to Map function.
I want to Print this result.
payload["do"]=10
payload["f1"]=20
payload["f2"]=30
var kvArray = [{key: 1, value: 10},
{key: 2, value: 20},
{key: 3, value: 30}];
var reformattedArray = kvArray.map(obj =>{
var payload = {};
const mapping = [null, 'rt', 'do', 'f1'];
const key = mapping[obj.key];
payload[key] = obj.value;
return payload;
});
console.log(reformattedArray);
You could use a destructuring assignment and build a new object with computed property names.
For the final keys, you could use an object keys with corresopnding keys to the the keys of the given object.
var kvArray = [{ key: 1, value: 10 }, { key: 2, value: 20 }, { key: 3, value: 30 }],
keys = { 1: 'rt', 2: 'do', 3: 'fi' },
result = kvArray.map(({ key, value }) => ({ [keys[key]]: value }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I'm not sure what format you want.
try the code below:
var kvArray = [{ key: 1, value: 10 },
{ key: 2, value: 20 },
{ key: 3, value: 30 }];
var reformattedArray = kvArray.map(obj => obj.value);
console.log(reformattedArray)
the result will be:
[ 10, 20, 30 ]
Not sure what you are trying to achieve with lines:
payload["rt"];
payload["do"];
payload["f1"];
If you want to create new keys in the reformatterArray, try assigning a value, eg.
var kvArray = [{key: 1, value: 10},
{key: 2, value: 20},
{key: 3, value: 30}];
var reformattedArray = kvArray.map(obj =>{
var payload = {};
payload["rt"] = "";
payload["do"]= "";
payload["f1"]= "";
payload[obj.key] = obj.value;
console.log(payload["rt"]);
return payload;
});
console.log(reformattedArray):
//result
0: {1: 10, rt: "", do: "", f1: ""}
1: {2: 20, rt: "", do: "", f1: ""}
2: {3: 30, rt: "", do: "", f1: ""}
You were assigning the value to payload but getting the values of payload.
var kvArray = [{key: 1, value: 10},
{key: 2, value: 20},
{key: 3, value: 30}];
var reformattedArray = kvArray.map(obj =>{
var payload = {};
payload[obj.key] = obj.value;
console.log(payload[obj.key]);
return payload;
});
You are mapping data to reformattedArray , so you need to pring reformattedArray to get values,
var kvArray = [{key: 1, value: 10},
{key: 2, value: 20},
{key: 3, value: 30}];
var reformattedArray = kvArray.map(obj =>{
var payload = {};
payload[obj.key] = obj.value;
return payload;
});
console.log(reformattedArray);
Also you have following code which is of no use
payload["rt"];
payload["do"];
payload["f1"];
This code works fine
let kvArray = [{key: 1, value: 10},
{key: 2, value: 20},
{key: 3, value: 30}];
let reformattedArray = kvArray.map(obj =>{
var payload = {};
payload[obj.key] = obj.value;
return payload;
});
console.log(reformattedArray)
The above code print output like this
[
0: {1: 10}
1: {2: 20}
2: {3: 30}
]
For more info, refer this link

Convert array of objects to one Object using ramda.js

I have an array:
var a = [
{id: 1, val: 'a'},
{id: 2, val: 'b'},
{id: 3, val: 'c'},
{id: 4, val: 'd'},
]
And I want to get transform it to:
var b = {
1: 'a',
2: 'b',
3: 'c',
4: 'd',
}
Actually I'm using pure js:
var b = a.reduce(
(ac, pr) => ({
...ac,
[pr.id]: pr.val,
}),
{}
);
But maybe Ramda.js have something special for that purpose?
You are looking for Ramda's .mergeAll() method:
var b = R.mergeAll(a.map(function(o) {
return {
[o.id]: o.val
}
}));
The .map()call will return the custom object from each item, taking only the values, then .mergeAll() will merge the array into one object.
mergeAll Documentation:
Merges a list of objects together into one object.
Demo:
var a = [{
id: 1,
val: 'a'
},
{
id: 2,
val: 'b'
},
{
id: 3,
val: 'c'
},
{
id: 4,
val: 'd'
},
];
var b = R.mergeAll(a.map(function(o) {
return {
[o.id]: o.val
}
}));
console.log(b);
<script src="https://cdn.jsdelivr.net/ramda/0.18.0/ramda.min.js"></script>
If anyone still passes by here, it does indeed:
R.indexBy(R.prop('id'), someArray);
See indexBy in Ramda's documentation
EDIT:
Bennet is correct. If we want val as the only value per key, we can "pluck" it out after:
const createValDict = R.pipe(
R.indexBy(R.prop('id')),
R.pluck('val')
)
const valDict = createValDict(myArr)
Pluck works on objects too
Get the ordered values from each object by mapping with R.props, and use R.fromPairs to create an object:
var a = [
{id: 1, val: 'a'},
{id: 2, val: 'b'},
{id: 3, val: 'c'},
{id: 4, val: 'd'},
];
var result = R.compose(R.fromPairs, R.map(R.props(['id', 'val'])));
console.log(result(a));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
With plain Javascript, you could use a combination with Object.assign, spread syntax ..., Array#map, destructuring assignment and short hand properties.
var a = [{ id: 1, val: 'a' }, { id: 2, val: 'b' }, { id: 3, val: 'c' }, { id: 4, val: 'd' }],
result = Object.assign(...a.map(({ id, val }) => ({ [id]: val })));
console.log(result);
var a = [
{id: 1, val: 'a'},
{id: 2, val: 'b'},
{id: 3, val: 'c'},
{id: 4, val: 'd'},
]
var result = {};
for (var i=0; i<a.length; i++) {
result[a[i].id] = a[i].val;
}
console.log(result);
If you wanted something point-free, you could write:
const combine = compose(mergeAll, map(lift(objOf)(prop('id'), prop('val'))))
const {compose, mergeAll, map, lift, objOf, prop} = R;
const combine = compose(mergeAll, map(lift(objOf)(prop('id'), prop('val'))))
var a = [{id:1, val:'a'}, {id:2, val:'b'}, {id:3, val:'c'}, {id:4, val:'d'}]
console.log(combine(a));
<script src="https://cdn.jsdelivr.net/ramda/0.18.0/ramda.min.js"></script>
Here it works like a charm :
var a = [
{id: 1, val: 'a'},
{id: 2, val: 'b'},
{id: 3, val: 'c'},
{id: 4, val: 'd'},
];
// var b = R.fromPairs( a.map(Object.values) );
// Perhaps this is the more general and order independent way:
var b = R.fromPairs(a.map( ({id,val})=>[id,val] ));
console.log( b );
<script src="//cdn.jsdelivr.net/npm/ramda#latest/dist/ramda.min.js"></script>
This might be the simplest way:
pipe(map(props(['id', 'val'])), fromPairs)(a)
#spflow's answer is simpler but not guaranteed to work on all platforms. Ramda code golf is always fun!
const { fromPairs, map, pipe, props } = R
const a = [
{id: 1, val: 'a'},
{id: 2, val: 'b'},
{id: 3, val: 'c'},
{id: 4, val: 'd'},
]
const result = pipe(map(props(['id', 'val'])), fromPairs)(a)
console.log(result)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.min.js"></script>
Yet one approach:
const { indexBy, prop, pipe, pluck } = R
const a = [
{id: 1, val: 'a'},
{id: 2, val: 'b'},
{id: 3, val: 'c'},
{id: 4, val: 'd'},
]
const result = pipe(indexBy(prop('id')), pluck('val'))(a)
console.log(result)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.min.js"></script>
Simplest, point-free:
compose(fromPairs, map(values))(a)
const { compose, fromPairs, map, values } = R
const a = [
{id: 1, val: 'a'},
{id: 2, val: 'b'},
{id: 3, val: 'c'},
{id: 4, val: 'd'},
]
const result = compose(fromPairs, map(values))(a)
console.log(result)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

Merge 2 object with same key, value from 2 array

I want to merge 2 object with same key, value from 2 array, something like this:
var arr1 = [
{ a: "a", 1: 1, 2: 2 },
{ a: "b", 1: 1, 2: 3 }
];
var arr2 = [
{ a: "a", 3: 123 },
{ a: "b", 3: 4411 }
];
var arr3 = _.map(arr1, function(a1) {
var a3 = {};
_.map(arr2, function(a2) {
if (a1.a == a2.a) {
a3 = _.extend(a1, a2);
}
})
return a3
});
result:
arr3 = [
{ '1': 1, '2': 2, '3': 123, a: 'a' },
{ '1': 1, '2': 3, '3': 4411, a: 'b' }
]
Does it look stupid? Are there any others ways to do this?
Thanks for reading.
Use a lodash chain to concat the arrays, group similar objects, and then merge each group to a single object:
var arr1 = [{ a: "a", 1: 1, 2: 2 }, { a: "b", 1: 1, 2: 3 }];
var arr2 = [{ a: "a", 3: 123 }, { a: "b", 3: 4411 }];
var result = _(arr1)
.concat(arr2) // concat the 2nd array
.groupBy('a') // group by the identical key
.map(_.spread(_.curry(_.merge, {}))) // left currey merge to to create a new empty object, and spread the group as parameters
.value();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
With ES6 you can use Array#reduce to collect the similar objects in a Map, then get the Map#values iterator, and use the spread syntax to convert to an array:
const arr1 = [{ a: "a", 1: 1, 2: 2 }, { a: "b", 1: 1, 2: 3 }];
const arr2 = [{ a: "a", 3: 123 }, { a: "b", 3: 4411 }];
const result = [...arr1.concat(arr2) // concat the arrays
.reduce((m, o) => m.set(o.a, Object.assign(m.get(o.a) || {}, o)), // use a map to collect similar objects
new Map()
).values()]; // get the values iterator of the map, and spread into a new array
console.log(result);
you can do
var arr1 = [
{ a: "a", 1: 1, 2: 2 },
{ a: "b", 1: 1, 2: 3 }
];
var arr2 = [
{ a: "a", 3: 123 },
{ a: "b", 3: 4411 }
];
let result = arr1.map((e) => {
for(let element of arr2){
if(e.a == element.a) Object.assign(e, element);
}
return e;
});
console.log(result);

Categories

Resources