Remove specific element from array of specifc object [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I need to modify a nested array. In this example I would like to remove content 2 from the target array of the object with the id ZFrNsQKSY6ywSzYps
var array = [
{ _id: "QKSY6ywSzYpsZFrNs", target: ["content 1"]}
{ _id: "ZFrNsQKSY6ywSzYps", target: ["content 1", "content 2"]}
{ _id: "SzYpsZFrNQKSY6yws", target: ["content 1"]}
]
I tried to use find() but with that I do not update the array. So this seems not to be the correct approach.

You can use find() method to get object and then indexOf() to find element in array that you want to remove and if found splice() method to remove it.
var array = [
{ _id: "QKSY6ywSzYpsZFrNs", target: ["content 1"]},
{ _id: "ZFrNsQKSY6ywSzYps", target: ["content 1", "content 2"]},
{ _id: "SzYpsZFrNQKSY6yws", target: ["content 1"]}
]
const obj = array.find(({_id}) => _id == 'ZFrNsQKSY6ywSzYps');
if(obj) {
const i = obj.target.indexOf('content 2');
if(i != -1) obj.target.splice(i, 1)
}
console.log(array)

var newarray = []
for(var i1 = 0; i1< array.length;i1++){
var subarray = []
for(var i2 = 0; i1<array[0].target.length;i++){
if(array[0].target[0]!="content 2"){ // or desired removed content
subarray.push(array[0].target[0])
}
}
newarray.push({"_id":array[0].id,"target":subarray})
}
after that simply access newarray

First: elements in array should be separated by commas.
Second: Is there some logic to update target arrays? If so you can iterate over the elements and modify their targets according to that logic.
Other than that you can always do this
array[1].target = ["content1"]

Try tihs approach:
const array = [
{ _id: "QKSY6ywSzYpsZFrNs", target: ["content 1"]},
{ _id: "ZFrNsQKSY6ywSzYps", target: ["content 1", "content 2"]},
{ _id: "SzYpsZFrNQKSY6yws", target: ["content 1"]}
]
console.log(array);
array.forEach(
item =>
// filter out the unwanted content
item.target = item.target.filter(
content => content !== "content 2"
)
)
console.log(array);

Related

JavaScript Replacing Object in Array with ID Number

So I have a series of objects that are pulled from an API and inputted into an array, something like such:
array = [
{id: 0, name: "First", relationship: "Friend"},
{id: 1, name: "Second", relationship: "Friend"}
]
The user is allowed to add and remove objects to the list freely (they will appear within a Vue.JS DataTable), and said user is allowed a maximum of 4 objects within the array (lets say 4 "friends")
How should I go about implementing a function that searches the existing array (say, if its populated from the API), and inputs the new object with the corresponding ID that is missing (so if the user deletes the object with the id 2, and adds another, it will search said array with objects, find the missing id 2 slot in the array, and input the object in its place)?
Previously I have gone about it via implement array.find() with conditionals to see if the array contains or does not contain the certain id value, however, it searches through each entry and can end up inserting the same object multiple times. Another method I haven't attempted yet would be having a separate map that contains ids, and then when a user removes an object, having it correspond with the map, and vice versa when adding.
Any suggestions? Thanks
Instead of an array, I'd keep an object in data. Have it keyed by id, like this:
let objects = {
0: { id: 0, name: 'name0', relationship: 'relationship0' },
1: { id: 1, name: 'name1', relationship: 'relationship1' },
}
Integer keys in modern JS will preserve insertion order, so you can think of this object as ordered. The API probably returns an array, so do this...
// in the method that fetches from the api
let arrayFromApi = [...];
this.objects = array.reduce((acc, obj) => {
acc[obj.id] = obj; // insertion order will be preserved
return acc;
}, {});
Your UI probably wants an array, so do this (refer to "array" in the markup):
computed: {
array() {
return Object.values(this.objects);
},
To create a new object, insert it in order, minding the available keys. Note this is a linear search, but with small numbers of objects this will be plenty fast
methods: {
// assumes maxId is const like 4 (or 40, but maybe not 400)
createObject(name, relationship) {
let object = { name, relationship };
for (let i=0; i< maxId; i++) {
if (!this.objects[i]) {
object.id = i;
this.objects[i] = object;
break;
}
}
try this,
let array = [
{id: 0, name: "First", relationship: "Friend"},
{id: 4, name: "Second", relationship: "Friend"},
{id: 2, name: "Second", relationship: "Friend"},
]
const addItem = (item) => {
let prevId = -1
// this is unnecessary if your array is already sorted by id.
// in this example array ids are not sorted. e.g. 0, 4, 2
array.sort((a, b) => a.id - b.id)
//
array.forEach(ob => {
if(ob.id === prevId + 1) prevId++
else return;
})
item = {...item, id: prevId + 1 }
array.splice(prevId+1, 0, item)
}
addItem({name: "x", relationship: "y"})
addItem({name: "a", relationship: "b"})
addItem({name: "c", relationship: "d"})
console.log(array)
You can simply achieve this with the help of Array.find() method along with the Array.indexOf() and Array.splice().
Live Demo :
// Input array of objects (coming from API) and suppose user deleted 2nd id object from the array.
const arr = [
{id: 0, name: "First", relationship: "Friend" },
{id: 1, name: "Second", relationship: "Friend" },
{id: 3, name: "Fourth", relationship: "Friend" }
];
// find the objects next to missing object.
const res = arr.find((obj, index) => obj.id !== index);
// find the index where we have to input the new object.
const index = arr.indexOf(res);
// New object user want to insert
const newObj = {
id: index,
name: "Third",
relationship: "Friend"
}
// Insert the new object into an array at the missing position.
arr.splice(index, 0, newObj);
// Output
console.log(arr);

I want to create an object of objects input with the results from looping an array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 months ago.
Improve this question
I want to construct a JSON object from the result obtained by iterating through the array below.
Here is the array list : Input
var input = [
{
bio: "Test",
id: 2,
image: "http://localhost:8000/media/default.jpg",
user: 2
},
{
bio: "Test2",
id: 3,
image: "http://localhost:8000/media/default.png",
user: 2
}
]
I want something like the below:
Expected output:
{
"Test": {
bio: "Test",
id: 2,
image: "http://localhost:8000/media/default.jpg",
},
"TestTwo": {
bio: "TestTwo",
id: 3,
image: "http://localhost:8000/mediafile/default.jpg",
}
}
I am able to get array of objects but not the exact format that I want. Need to call ajax with the same output.
var input = [
{
bio: "Test",
id: 2,
image: "http://localhost:8000/media/default.jpg",
user: 2
},
{
bio: "Test2",
id: 3,
image: "http://localhost:8000/media/default.png",
user: 2
}
];
const final = input.reduce((res, obj) => {
res[obj.bio] = obj;
return res;
}, {});
console.log(final);
Previous answer you asked to do the opposite, and my answer was:
Use Object.values, and add user property with value 2:
const input = {
Test: {
bio: "Test",
id: 2,
image: "http://localhost:8000/media/default.jpg",
},
TestTwo: {
bio: "TestTwo",
id: 3,
image: "http://localhost:8000/mediafile/default.jpg",
},
};
const objs = Object.values(input);
for (let obj of objs) {
obj.user = 2
}
console.log(JSON.stringify(objs, null, 4))
/*
[
{
"bio": "Test",
"id": 2,
"image": "http://localhost:8000/media/default.jpg",
"user": 2
},
{
"bio": "TestTwo",
"id": 3,
"image": "http://localhost:8000/mediafile/default.jpg",
"user": 2
}
]
*/
Other ways to add property user:
You could use Use Array.prototype.map()
objs = objs.map(obj => ({ ...obj, user: 2 }))
or use with more readable with object assign
objs = objs.map(obj => {
const userPropsObj = {
user: 2
};
return Object.assign(obj, userPropsObj);
});
The answer to this question which tend to return back to the initial input(object) instead of an array:
you could iterate over the array and delete user property we add and assign each object with bio as the key.
const input = [
{
bio: "Test",
id: 2,
image: "http://localhost:8000/media/default.jpg",
user: 2
},
{
bio: "Test2",
id: 3,
image: "http://localhost:8000/media/default.png",
user: 2
}
];
const output = {};
for (let obj of input) {
delete obj.user;
output[obj.bio] = obj;
}
console.log(output)
PS: Please, Don't delete the question as you did before because you delete the answers we did too, And maybe answers help someone else!
const obj = input.reduce((result, item) => { result[item.bio] = item;
return result;
}, {});
reduce is a higher-order function it takes a method as an argument that method contains the result and items in my example; it iterates over each item in the array and assigns the whole object value to the key we created which is item.bio accumulating all these keys will results in one object with the keys and values as needed.

Replace array of objects with new object [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
I have an array of objects and I would like to replace an object with a new object that has a specific id. My goal is to replace/remove the object where id === 'hotel' with an entirely new object and keep the same index.
Example / Current Code
const sampleArray = [{ id: 'price' }, { id: 'hotel1', filters: [] }, { id: 'type' }]
const index = sampleArray.findIndex((obj) => obj.id === 'hotel1') // find index
sampleArray = sampleArray.splice(index, 0) // remove object at this index
sampleArray.splice(index, 0, { id: 'hotel2' }) // attempt to replace with new object ... not working :(
You don't need the fancy splice logic. Just set the array element and forget it.
const sampleArray = [{ id: 'price' }, { id: 'hotel1', filters: [] }, { id: 'type' }]
const index = sampleArray.findIndex((obj) => obj.id === 'hotel1'); // find index
sampleArray[index] = { id: 'hotel2' }; // replace with new object ... working :)
console.log(JSON.stringify(sampleArray));
You can use the map() function:
const updatedArray = sampleArray.map(item => item.id === 'hotel' ? {...item, id: 'hotel2'} : item);
Another way, replacing an array element by index
const sampleArray = [{ id: 'price' }, { id: 'hotel1', filters: [] }, { id: 'type' }]
const index = sampleArray.findIndex((obj) => obj.id === 'hotel1'); // find index
Object.assign(sampleArray, { [index]: { id: 'hotel2' } }); // replace with new object
console.log(sampleArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

javascript/typescript get index of complex object in a multiple dimensional array

i want to get complete index of a complex object inside of a multiple dimensional array.
E.g. i have the following array.
var arr = [
{
name: "zero", children: null
},
{
name: "one", children: [
{
name: "one_zero", children: [{ name: "one_zero_zero", children: null }]
}
]
}
];
I want to get of the object with the name "one_zero_zero". It should be of indexes 1_0_0.
I hope you guys can help me with this problem.
Best regards,
var newarr =[];
var index = "";
function findmeinarr(s,arr){
for(let i in arr){
var name = "";
var flag = false;
name=arr[i].name
if(name==s){
index+=i;flag=true;
}
if(arr[i].children!=null){
newarr = arr[i].children;
index+=i+"-";
}
}
if(flag)console.log(index);
else findmeinarr(s,newarr);
}
Here is the working snippet for this :
https://codepen.io/sidhanshu28/pen/xzEyqZ
I am using recursive call here. Let me know if I can help more. Please mark it as solution, if it works for you.

How to form JavaScript object array? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to create a JavasScript array in following format:
var datas = [
{ name: "Peter Pan", location: "peter#pan.de" },
{ name: "Molly", location: "molly#yahoo.com" },
{ name: "Forneria Marconi", location: "live#japan.jp" },
{ name: "Master <em>Sync</em>", location: "205bw#samsung.com" }
];
As I want to create it dynamically, It would be great if I can create an array like that.
You just did it.
But if you mean adding objects one at a time you can do
var datas = [];
and then
newobj = //dynamically created object
datas.push(newobj);
var data = [];
data.push({ name: "Peter Pan", location: "peter#pan.de" },
{ name: "Molly", location: "molly#yahoo.com" },
{ name: "Forneria Marconi", location: "live#japan.jp" },
{ name: "Master <em>Sync</em>", location: "205bw#samsung.com" });
If you are receiving the object from some service, just call data.push(objectName);. You will have array of objects.
Fiddle for you.
http://jsfiddle.net/q69ku/
Have a look at:
How do I create JavaScript array (JSON format) dynamically?
var data = [];
data.push({ name: "Peter Pan", location: "peter#pan.de" });
// ...
data.push({name: "x" location:"y"})
you will need to change this to fit your data results
var arr = [];
var b = 20; // or your data results
for(i=0;i<b;i++){
var obj = {name: "Peter Pan", location: "peter#pan.de"};
arr.push(obj);
}

Categories