How can I edit the value of an array - javascript

I have an example:
var A = [{
key: "iphone",
value: "American"
}, {
key: "sony",
value: "Japan"
}]
I want to do this action:
B=[{value:"American"},{value:"Japan"}]
How can I do this? Help me.

Use Array.map and return a new Object with the value field,
DEMO
var A =[{key:"iphone",value:"American"},{key:"sony",value:"Japan"}] ;
var result = A.map(d => ({ value: d.value }));
console.log(result);

var B = A.map(function(obj) { return { value: obj.value }; });
or
var B = A.map(obj => ({ value: obj.value }));

Maybe you prefer this more readable syntax?
function myObjectConverter (inputObject) {
var outputObject = {};
// ignore the key property
outputObject.Country1 = inputObject.value1;
outputObject.Country2 = inputObject.value2;
outputObject.Country3 = inputObject.value3;
outputObject.Country4 = inputObject.value4;
// transfer any other items with new names
return outputObject;
}
var B = A.map(myObjectConverter);

Related

Create object from multiple object with same value in map JS [duplicate]

I have an array of objects:
[
{ key : '11', value : '1100', $$hashKey : '00X' },
{ key : '22', value : '2200', $$hashKey : '018' }
];
How do I convert it into the following by JavaScript?
{
"11": "1100",
"22": "2200"
}
Tiny ES6 solution can look like:
var arr = [{key:"11", value:"1100"},{key:"22", value:"2200"}];
var object = arr.reduce(
(obj, item) => Object.assign(obj, { [item.key]: item.value }), {});
console.log(object)
Also, if you use object spread, than it can look like:
var object = arr.reduce((obj, item) => ({...obj, [item.key]: item.value}) ,{});
One more solution that is 99% faster is(tested on jsperf):
var object = arr.reduce((obj, item) => (obj[item.key] = item.value, obj) ,{});
Here we benefit from comma operator, it evaluates all expression before comma and returns a last one(after last comma). So we don't copy obj each time, rather assigning new property to it.
This should do it:
var array = [
{ key: 'k1', value: 'v1' },
{ key: 'k2', value: 'v2' },
{ key: 'k3', value: 'v3' }
];
var mapped = array.map(item => ({ [item.key]: item.value }) );
var newObj = Object.assign({}, ...mapped );
console.log(newObj );
One-liner:
var newObj = Object.assign({}, ...(array.map(item => ({ [item.key]: item.value }) )));
You're probably looking for something like this:
// original
var arr = [
{key : '11', value : '1100', $$hashKey : '00X' },
{key : '22', value : '2200', $$hashKey : '018' }
];
//convert
var result = {};
for (var i = 0; i < arr.length; i++) {
result[arr[i].key] = arr[i].value;
}
console.log(result);
I like the functional approach to achieve this task:
var arr = [{ key:"11", value:"1100" }, { key:"22", value:"2200" }];
var result = arr.reduce(function(obj,item){
obj[item.key] = item.value;
return obj;
}, {});
Note: Last {} is the initial obj value for reduce function, if you won't provide the initial value the first arr element will be used (which is probably undesirable).
https://jsfiddle.net/GreQ/2xa078da/
Using Object.fromEntries:
const array = [
{ key: "key1", value: "value1" },
{ key: "key2", value: "value2" },
];
const obj = Object.fromEntries(array.map(item => [item.key, item.value]));
console.log(obj);
A clean way to do this using modern JavaScript is as follows:
const array = [
{ name: "something", value: "something" },
{ name: "somethingElse", value: "something else" },
];
const newObject = Object.assign({}, ...array.map(item => ({ [item.name]: item.value })));
// >> { something: "something", somethingElse: "something else" }
you can merge array of objects in to one object in one line:
const obj = Object.assign({}, ...array);
Use lodash!
const obj = _.keyBy(arrayOfObjects, 'keyName')
Update: The world kept turning. Use a functional approach instead.
Previous answer
Here you go:
var arr = [{ key: "11", value: "1100" }, { key: "22", value: "2200" }];
var result = {};
for (var i=0, len=arr.length; i < len; i++) {
result[arr[i].key] = arr[i].value;
}
console.log(result); // {11: "1000", 22: "2200"}
Simple way using reduce
// Input :
const data = [{key: 'value'}, {otherKey: 'otherValue'}];
data.reduce((prev, curr) => ({...prev, ...curr}) , {});
// Output
{key: 'value', otherKey: 'otherValue'}
More simple Using Object.assign
Object.assign({}, ...array);
Using Underscore.js:
var myArray = [
Object { key="11", value="1100", $$hashKey="00X"},
Object { key="22", value="2200", $$hashKey="018"}
];
var myObj = _.object(_.pluck(myArray, 'key'), _.pluck(myArray, 'value'));
Nearby 2022, I like this approach specially when the array of objects are dynamic which also suggested based on #AdarshMadrecha's test case scenario,
const array = [
{ key : '11', value : '1100', $$hashKey : '00X' },
{ key : '22', value : '2200', $$hashKey : '018' }];
let obj = {};
array.forEach( v => { obj[v.key] = v.value }) //assign to new object
console.log(obj) //{11: '1100', 22: '2200'}
let array = [
{ key: "key1", value: "value1" },
{ key: "key2", value: "value2" },
];
let arr = {};
arr = array.map((event) => ({ ...arr, [event.key]: event.value }));
console.log(arr);
Was did yesterday
// Convert the task data or array to the object for use in the above form
const {clientData} = taskData.reduce((obj, item) => {
// Use the clientData (You can set your own key name) as the key and the
// entire item as the value
obj['clientData'] = item
return obj
}, {});
Here's how to dynamically accept the above as a string and interpolate it into an object:
var stringObject = '[Object { key="11", value="1100", $$hashKey="00X"}, Object { key="22", value="2200", $$hashKey="018"}]';
function interpolateStringObject(stringObject) {
var jsObj = {};
var processedObj = stringObject.split("[Object { ");
processedObj = processedObj[1].split("},");
$.each(processedObj, function (i, v) {
jsObj[v.split("key=")[1].split(",")[0]] = v.split("value=")[1].split(",")[0].replace(/\"/g,'');
});
return jsObj
}
var t = interpolateStringObject(stringObject); //t is the object you want
http://jsfiddle.net/3QKmX/1/
// original
var arr = [{
key: '11',
value: '1100',
$$hashKey: '00X'
},
{
key: '22',
value: '2200',
$$hashKey: '018'
}
];
// My solution
var obj = {};
for (let i = 0; i < arr.length; i++) {
obj[arr[i].key] = arr[i].value;
}
console.log(obj)
You can use the mapKeys lodash function for that. Just one line of code!
Please refer to this complete code sample (copy paste this into repl.it or similar):
import _ from 'lodash';
// or commonjs:
// const _ = require('lodash');
let a = [{ id: 23, title: 'meat' }, { id: 45, title: 'fish' }, { id: 71, title: 'fruit' }]
let b = _.mapKeys(a, 'id');
console.log(b);
// b:
// { '23': { id: 23, title: 'meat' },
// '45': { id: 45, title: 'fish' },
// '71': { id: 71, title: 'fruit' } }

how to add objects to arrays

I'm trying to construct an array of objects from a set of two different arrays. I'm a little comfussed on where I need to go from here.
I'm creating a unique key value, but the object is going into the array individual.
const startingArray = [
{
key: "description",
value: "my description"
},
{
key: "description2",
value: "my description2"
},
{
key: "description3",
value: "my description3"
},
]
my logic
const k = mystartingArray.reduce((acc, d, count) => {
const name = Object.value(d)[0]
const title = Object.value(d)[1]
const value = {
[name]: title
}
acc.push(value)
return acc
},[])
how I want the Array to look
const finishedArray = [
{
description: "my description",
description2: "my description2,
description3: "my description3,
}
How far am I off?
I think this would be simpler to solve just by using a basic forEach.
let value = {};
startingArray.forEach(obj => {
value[obj.key] = obj.value;
});
const finishedArray = [value];
Or, if you don't want to have a value object:
const finishedArray = [{}];
startingArray.forEach(obj => {
finishedArray[0][obj.key] = obj.value;
});
const finishedArray = [
startingArray.reduce((a, v) => {a[v.key] = v.value; return a}, {})
]
To finish your code:
const startingArray = [
{
key: "description",
value: "my description"
},
{
key: "description2",
value: "my description2"
},
{
key: "description3",
value: "my description3"
},
];
const k = startingArray.reduce((acc, d, count) => {
return [{
...(acc[0] || {}),
[d.key]: d.value
}]
},[])
console.log(k);
However, I think the solution of Rocket Hazmat is more reasonable than this.

Perform .join on a complex object with array of object dynamically

I have a complex js object, that contains arrays of an object. The problem is some of the main object properties' arrays can have a different property.
var foo = {};
foo.prop1 = [
{name:"test", skill:1},
{name:"test2", skill:2},
];
foo.prop2 = [
{address:"Earth",distance:1},
{address:"Mars", distance:2}
]
My aim is to just replace the main object property value with the joined values for retrieval.
This is what I have right now.
if(Object.keys(foo).length){
Object.keys(foo).forEach(key => {
var x = foo[key];
if(key === "address") {
foo[key] = x.map(function(elem){return elem.address;}).join(";");
} else {
foo[key] = x.map(function(elem){return elem.name;}).join(";");
}
});
}
How can I make it dynamic so that I don't need to use the if statement? I just want to join all the first property of the inner obj.
Result:
foo new values would be:
foo.prop1 = test;test2
foo.prop2 = Earth;Mars
I got it. I just want to join the first property of the sub object.
I replaced the if with this
foo[key] = x.map(function(elem){return elem[Object.keys(elem)[0]]; }).join(";");
I guess you are trying to choose the value with string type
var foo = {};
foo.prop1 = [{
name: "test",
skill: 1
},
{
name: "test2",
skill: 2
},
];
foo.prop2 = [{
address: "Earth",
distance: 1
},
{
address: "Mars",
distance: 2
}
]
function formulate() {
const result = {};
(Object.keys(foo) || []).forEach(function(k) {
result[k] = foo[k].map(function(val) {
str_key = Object.keys(val).filter(function(val_k) {
return typeof val[val_k] === "string";
});
return str_key.map(function(s) {
return val[s];
});
}).join(";");
});
return result;
}
result = formulate()
console.log(result);
I hope, this will work for you
var foo = {};
foo.prop1 = [
{name:"test", skill:1},
{name:"test2", skill:2},
];
foo.prop2 = [
{address:"Earth",distance:1},
{address:"Mars", distance:2}
]
Object.keys(foo).forEach(key => {
foo[key]=foo[key].map(val => { return Object.entries(val)[0][1] } ).toString().split(",").join(";")
});
console.log(foo)

I want to get all the values in an object with a same field name and store in an array

I have this object and I want to get only a specific value in object
input
var lst = [
{
name: "foo",
value: "fooValue"
},
{
name: "bar",
value: "barValue"
}
];
output:
var b = ["foo", "bar"];
You can use Array.prototype.map()
var lst = [
{
name: "foo",
value: "fooValue"
},
{
name: "bar",
value: "barValue"
}
];
var b = lst.map(ob => ob.name);
console.log( b )
Try following using Array.map
var lst = [{name: "foo", value: "fooValue"},{name: "bar",value: "barValue"}];
var output = lst.map(({name}) => name);
console.log(output);
If you're going to do this often, it might help to make a reusable function out of this. A common name for this operation is pluck.
const pluck = (prop) => (xs) => xs.map(x => x[prop])
const lst = [{name: "foo", value: "fooValue"}, {name: "bar", value: "barValue"}]
const allNames = pluck('name')
console.log(allNames(lst));
// or just
console.log(pluck('name')(lst))
You can use object destructuring to simply pull out the value you're looking to append to your array.
array.forEach(({name}) => b.push(name));
var b = [], lst = [{name: "foo",value: "fooValue"},{name: "bar",value: "barValue"}]
.forEach(({name}) => b.push(name));
console.log(b);

angularjs: check if value exists in array of objects

var a = [ { id:1}, {id:2} ];
var b = {id:1};
var res = a.indexOf(b._id) == -1;
console.log(res);
I want to check if b._id is in a[].
Note: a[] is an array of objects
Try this..
var a = [{ id:1}, {id:2}];
var b={id:1};
var arrayWithIds = a.map(function(x){
return x.id
}); // get new array contains all ids
var present = arrayWithIds.indexOf(b.id) != -1 // find the b.id array
console.log(present);
Here is the reference for Map and indexOf
This should work :
var a = [ { id:1} ,{id:2} ];
var b={id:1}
console.log(a.findIndex(function(obj){return obj.id=b.id}))
indexOf works when you are dealing with indexed arrays not with array of objects.
Please use the following code:
var a = [ { id:1}, {id:2} ];
var b={id:1}
function findMatch(element) {
return element.id === b.id;
}
console.log(a.findIndex(findMatch));
A better way is using .find function.
let a = [{
id: 1
}, {
id: 2
}],
b = {
id: 1
},
obj = a.find(function(itm) {
return itm.id == b.id;
});
console.log(obj)
And also using .findIndex function to get just index of item in array.
let a = [{
id: 1
}, {
id: 2
}],
b = {
id: 1
},
objIndex = a.findIndex(function(itm) {
return itm.id == b.id;
});
console.log(objIndex)
And for getting all objects with that condition use .filter function.
let a = [{
id: 1
}, {
id: 2
}],
b = {
id: 1
},
objArr = a.filter(function(itm) {
return itm.id == b.id;
});
console.log(objArr)
Array.map() function compare id and its value and return a Boolean value if map as commented by #Slava Utesinov
var a = [{id: 1}, {id: 2}];
var b = {id: 1};
if(a.map(x => x.id).indexOf(b.id) != -1){
console.log("Exists");
}else{
console.log("Not exists");
}
try this
var a = [ { id:1} ,{id:2} ];
var b={id:1}
console.log(a.find(x=>x.id==b.id))// return matched record
var a = [ { id:1} ,{id:2} ];
var b={id:3}
console.log(a.find(x=>x.id==b.id)) //return undefined
Use Array.map() function of JavaScript to check it. It will compare id and its value as well.
Below is working code:
var a = [{
id: 1
}, {
id: 2
}];
var b = {
id: 1
};
if (a.map(x => x.id).indexOf(b.id) != -1) {
console.log("Available");
} else {
console.log("Not available");
}
You can use Filter of AngularJS
var a = [{id:1}, {id:2}];
var b = {id:1};
var found = false;
var filterResult = $filter('filter')(a, {id: b.id}, true);
if (filterResult.length > 0) {
found = true;
}

Categories